我必須編寫一個程序,將羅馬數字轉換為其相應的整數值,但我不斷收到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);
3 回答

三國紛爭
TA貢獻1804條經驗 獲得超7個贊
其他人對原因的看法是正確的。我認為你可以設置(根據命名約定應該是)一個虛擬值,該值與羅馬數字中使用的任何字母都不匹配,以防沒有任何下一個字符:next_charnextChar
char nextChar;
if (i + 1 < n1.length) {
nextChar = n1[i + 1];
} else {
nextChar = '\0';
}
通過此更改,您的程序將打?。?/p>
Roman Numeral:
CXIII
Number:
113
維托爾SRG也是正確的,你的程序缺乏驗證,這是不好的。
添加回答
舉報
0/150
提交
取消