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;
}