我有这种方法应该将罗马数字转换为整数,但是当我输入罗马数字时,它会切掉第一个字母,所以当我输入“IV”时,我得到 5 而不是 4。早些时候我有同样的问题,但只有它切断了最后一个字母,但我修复了它。这是下面粘贴的方法。谢谢你。如果您发现任何其他错误,请告诉我。
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;
}