Java 罗马数字到整数转换器中的ArrayIndexOutOfBoundsException
我必须编写一个程序,将一个罗马数字转换为相应的整数值,但我一直得到一个java.lang.ArrayIndexOutOfBoundsException错误。每当我更改某个内容时,它就会输出错误的值。有人能告诉我哪里出了问题吗Java 罗马数字到整数转换器中的ArrayIndexOutOfBoundsException,java,arrays,indexoutofboundsexception,Java,Arrays,Indexoutofboundsexception,我必须编写一个程序,将一个罗马数字转换为相应的整数值,但我一直得到一个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[
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);
charn1[]={'C','X','I','I','I'};
int结果=0;
对于(int i=0;i
导致数组越界。您可以再次模拟for循环以检查此索引
char next_char = n1[i + 1];
您的
for
循环从i=0
到i=n1.length-1
,因此
char next_char = n1[i + 1];
将始终导致ArrayIndexOutOfBoundsException
异常
从中,罗马数字最多由三个独立的组组成:
我建议您分别分析它们。关于原因,其他人是正确的。我认为您可以将
next\u char
(根据命名约定,它应该是nextChar
)设置为一个虚拟值,在没有任何next char的情况下,该值与罗马数字中使用的任何字母都不匹配:
char nextChar;
if (i + 1 < n1.length) {
nextChar = n1[i + 1];
} else {
nextChar = '\0';
}
Vitor SRG也正确地指出,您的程序缺少验证,这是不好的。请发布stacktrace,并告诉我们stacktrace指的是程序中的哪一行。总是在询问异常时。这些信息将使我们更容易发现哪里出了问题。
Roman Numeral:
CXIII
Number:
113