0

I'm taking an AP Computer Science course, and I'm having a problem with this code. We're to make a method that converts Roman Numeral Strings into decimal values.

So far, we've only gotten to if/else statements and while loops. I've seen a few answers here using switch, but our class hasn't gotten there yet. I need a way to do this without using switch. I've only written code assuming that the Roman Numerals are in non-ascending order, but whenever a string like "MM" is used, the method returns "0" as a value. Anyone know why this happens here?

Any tips on subtracting the numerals would also be appreciated.

   public int decimalValue ( String roman ){
     //given a Roman Numeral
     int decimal =0;
     int a = 0; // a and b used as to check each letter in String roman
     int b = 1;

     // Assuming in non-ascending order. Need to make for ascending
     while ( (a <= (roman.length() - 1) ) && (b <= roman.length() ) ) {
        if ( roman.substring(0,1) == "M") {
           decimal = decimal + 1000;
        }
        else if ( roman.substring(0,1) == "D") {
           decimal = decimal + 500;
        }
        else if ( roman.substring(0,1) == "C") {
           decimal = decimal + 100;
        }
        else if ( roman.substring(0,1) == "L") {
           decimal = decimal + 50;
        }
        else if ( roman.substring(0,1) == "X") {
           decimal = decimal + 10;
        }
        else if (roman.substring(0,1) == "V") {
           decimal = decimal + 5;
        }
        else if (roman.substring(0,1) == "I") {
           decimal = decimal + 1;
        }
        a++;
        b++;
        }

  return decimal;
  }
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170

1 Answers1

3

A few things:

  1. You don't need two counting variables a and b. One is enough
  2. You want to check characters of the String, so you should use roman.charAt(a) to check the character at position a in the string
  3. chars (and other primitive types) you compare with ==, Strings you have to compare with .equals()
  4. Right now with roman.substring(0,1) you are just checking the first character of the string, so you want to change that to roman.substring(a, a+1) or use characters as I wrote in 2. This way you will keep checking one character after the other.
  5. You should also think about numbers like IX, these ones you don't recognize yet ;)
Blub
  • 3,762
  • 1
  • 13
  • 24