Home > Back-end >  I dont understand why my Java code isnt reading IX as 9 but is reading LIX as 59
I dont understand why my Java code isnt reading IX as 9 but is reading LIX as 59

Time:09-12

I am trying to create some code to read roman numerals and turn them into an integer. the issue im having is the 9s and 4s. I am able to get it to read if the 9 or 4 is inside a number (I.E LIV is 54 and LXI is 59) but by its self (IV and IX) it only reads 6 and 11. here is my code:

public static void RomantoInt(String s) {
    HashMap<Character, Integer> RomanNums = new HashMap<>();
    int count = 0;

    RomanNums.put('I', 1);
    RomanNums.put('V', 5);
    RomanNums.put('X', 10);
    RomanNums.put('L', 50);
    RomanNums.put('C', 100);
    RomanNums.put('D', 500);
    RomanNums.put('M', 1000);


    LinkedList<Character> UserInput = new LinkedList<>();

    //Adds Each numeral to the Array
    for (int i = 0; i < s.length(); i  ) {
        char userint = s.charAt(i);
        UserInput.add(userint);
    }

    //loop through the array backwards and adds up the count.
           for(int j =UserInput.toArray().length -1; j> -1 ; j--) {
               int grab = RomanNums.get(UserInput.get(j));
               count  = grab;

   // Checks for 4s and 9s.

               if(grab == RomanNums.get('X') && (j - 1) == RomanNums.get('I')) {
                   count -= 2;
               }
    }
    System.out.println(count);

CodePudding user response:

Comparing j - 1 -- which is a position in a string -- to the value of a roman numeral does not seem to make any sense.

Specifically, it only works when the roman 'I' is the second character, exactly.

What you really want to be testing is whether the character at the (j-1)'th position is 'I'.

I don't understand your title, however. "Allowing the zero to be read". There is no Roman numeral for zero. You code says nothing about zeroes.

CodePudding user response:

You can try UserInput.get(j-1) instead of (j - 1) in your if statement because (j-1) is a static value.

  • Related