我必须编写一个程序,将罗马数字转换为其相应的整数值,但我不断收到java.lang.Array索引出界异常错误。每当我更改某些内容时,它就会输出错误的值。有人可以让我知道我哪里出错了吗?
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);
三国纷争
largeQ
一只萌萌小番薯
相关分类