2 回答

TA貢獻1898條經驗 獲得超8個贊
您test = test.replace(roman[i], "");將所有出現的“C”替換為“”,因此在找到第一個“C”并將總數加 100 后,您將消除所有剩余的“C”,并且從不計算它們。因此,您實際上計算了 的值"DCXV",即615。
您應該只替換roman[i]起始索引為 0 的出現,您可以通過替換來實現:
test = test.replace(roman[i], "");
和:
test = test.substring(roman[i].length()); // this will remove the first 1 or 2 characters
// of test, depending on the length of roman[i]
以下:
int result = 0;
int[] decimal = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
// Test string, the number 895
String test = "DCCCXCV";
for (int i = 0; i < decimal.length; i++ ) {
while (test.indexOf(roman[i]) == 0) {
result += decimal[i];
test = test.substring(roman[i].length());
}
}
System.out.println(result);
印刷:
895

TA貢獻1802條經驗 獲得超5個贊
test = test.replace(roman[i], "");
這將替換每次出現。相反,您應該只截斷字符串開頭(位置 0)的出現。
嘗試使用substring
而不是替換,并將長度作為參數傳遞roman[i]
添加回答
舉報