0
import java.util.HashMap;

public class Rtoi{

    private HashMap<Character,Integer> rn = new HashMap<Character,Integer>();
    Character[] input;
    Integer result;
    //constructor
    public Rtoi(){
        rn.put('I', 1);
        rn.put('V', 5);
        rn.put('X', 10);
        rn.put('L', 50);
        rn.put('C', 100);
        rn.put('D', 500);
        rn.put('M', 1000);
    }
    public Integer convert(String num){
  
        //read frm right to left
        for(int i=num.length()-1;i<0;i--){
            Character current =num.charAt(i);
            Character next =num.charAt(i-1);
            if(rn.get(current)<=rn.get(next)){
                result += rn.get(current);
            }
            else{
                result -= rn.get(current);
            }
        }
        return result;

    }
}

The method convert get a string of roman num to convert to integer but it return a default value result

tested using the string = "MMXVIII"

David
  • 21
  • 1
  • 2
    This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Jan 09 '23 at 13:55
  • And note: or you just add print statements. If you dont understand what your code is doing then first use a piece of paper an write down what you THINK you should happen and then have your code PRINT what is doing to... – GhostCat Jan 09 '23 at 13:57
  • Check the for-loop's condition. That will only be true when `num` is empty (and then it will remain true until `i` overflows from `Integer.MIN_VALUE` to `Integer.MAX_VALUE`). – Rob Spoor Jan 09 '23 at 14:43
  • if the `result` is `null` I would suspect that: it is never being initialized; and that the loop is never being executed || Hints: there is no reason for `result` to be a field instead of a local variable; no reason for it to be `Integer` instead of `int` (same for return type of method); check the condition of the `for` loop (it is not meant for be the terminating condition, but the condition for looping) – user16320675 Jan 09 '23 at 15:24

0 Answers0