I have this method which is supposed to convert roman numerals into integers, however when I put in roman numerals it chops off the first letter, so when I put in "IV", I get 5 rather than 4. Earlier I had the same issue, but only it was chopping off the last letter, but I fixed it. Here is the method pasted below. Thank you. Also please let me know if you notice any other errors.
public int romanToArabic()
{
int sum = 0;
int i;
for(i=0; i<=roman.length()-1; i++)
{
char rom = roman.charAt(i);
switch(rom)
{
case 'M':
sum += 1000;
break;
case 'D':
sum += 500;
break;
case 'C':
if(i < roman.length()-1)
{
char next = roman.charAt(i+1);
if(next == 'M')
{
sum += 900;
i++;
}
if(next == 'D')
{
sum +=400;
i++;
}
else
{
sum += 100;
}
}
else
{
sum += 100;
}
break;
case 'L':
sum += 50;
break;
case 'X':
if(i < roman.length()-1)
{
char next = roman.charAt(i+1);
if(next == 'L')
{
sum += 40;
i++;
}
if(next == 'C')
{
sum += 90;
i++;
}
else
{
sum += 10;
}
}
else
{
sum += 10;
}
break;
case 'V':
if( i < roman.length()-1)
{
char next = roman.charAt(i+1);
if(next == 'I')
{
sum += 6;
i++;
}
else
{
sum += 5;
}
}
else
{
sum += 5;
}
break;
case 'I':
if(i < roman.length()-1)
{
char next = roman.charAt(i+1);
if(next == 'V')
{
sum += 4;
i++;
}
if(next == 'X')
{
sum += 9;
i++;
}
else
{
sum += 1;
}
}
else
{
sum += 1;
}
break;
default:
System.out.println("I've encountered an issue with the characters you've entered.");
}
}
return sum;
}
It looks like you're missing an else. It's not really "chopping" off the first integer, but it may seem that way since
sum += 1
will be called when it shouldn't -- e.g., turning a 4 into a 5.You may have the same mistake for the other cases as well.