我必须编写一个程序,将罗马数字转换为相应的整数值,但我不断收到java.lang.ArrayIndexOutOfBoundsException错误。任何时候我改变一些东西,然后输出错误的值。有人能让我知道我哪里出错吗?
char n1[] = {'C', 'X', 'I', 'I', 'I'};
int result = 0;
for (int i = 0; i < n1.length; i++) {
char ch = n1[i];
char next_char = n1[i + 1];
if (ch == 'M') {
result += 1000;
} else if (ch == 'C') {
if (next_char == 'M') {
result += 900;
i++;
} else if (next_char == 'D') {
result += 400;
i++;
} else {
result += 100;
}
} else if (ch == 'D') {
result += 500;
} else if (ch == 'X') {
if (next_char == 'C') {
result += 90;
i++;
} else if (next_char == 'L') {
result += 40;
i++;
} else {
result += 10;
}
} else if (ch == 'L') {
result += 50;
} else if (ch == 'I') {
if (next_char == 'X') {
result += 9;
i++;
} else if (next_char == 'V') {
result += 4;
i++;
} else {
result++;
}
} else { // if (ch == 'V')
result += 5;
}
}
System.out.println("Roman Numeral: ");
for (int j = 0; j < n1.length; j++)
{
System.out.print(n1[j]);
}
System.out.println();
System.out.println("Number: ");
System.out.println(result);
其他人对事业是正确的。我想你可以将next_char
(根据命名约定应该是nextChar
)设置为一个虚拟值,在没有任何下一个char的情况下,它与罗马数字中使用的任何字母都不匹配:
char nextChar;
if (i + 1 < n1.length) {
nextChar = n1[i + 1];
} else {
nextChar = '\0';
}
通过此更改,您的程序将打印:
Roman Numeral: CXIII Number: 113
Vitor SRG也是正确的,你的程序缺乏验证,这是不好的。
你的for
循环从i = 0
到i = n1.length - 1
,所以这一行
char next_char = n1[i + 1];
将永远导致ArrayIndexOutOfBoundsException
例外。
从wikipedia,罗马数字由最多三个独立的小组组成:
我建议你分别解析它们。
这导致数组超出界限。您可以再次模拟for循环以检查此索引
char next_char = n1[i + 1];