大家好,我正在写一个从罗马数字到阿拉伯数字的转换程序。但是,stringindexoutofboundsexception始终存在问题:字符串索引超出范围:-1。下面是我的代码
package com.company;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println(romanToArabic("CIV"));
}
public static int romanToArabic(String romanNumeral){
Map <Character, Integer> map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int result = 0;
for (int i=0; i < romanNumeral.length(); i++){
int current = map.get(romanNumeral.charAt(i));
int next = map.get(romanNumeral.charAt(i-1));
if (i>0 && current > next){
result += current - 2*next;
}
result += current;
}
return result;
}
3条答案
按热度按时间w46czmvw1#
当“i=0”时,问题出现在第一次“for循环”迭代中
在下一行中,您可以得到一个索引为“0”的字符“c”
然后在下一行,当代码执行语句时,“i”变为-1(i-1)
因此,你试图得到一个索引为“-1”的字符
接下来是字符串索引out bound异常
因为字符串索引从零开始
2nc8po8w2#
当您第一次穿过回路时,“i-1”为-1(i=0)
qltillow3#
正如两人提到的,你从i=0开始,然后尝试(i-1)的运算,
通过在i=1处开始循环或仅执行这一行(以及代码的其余部分)来修复此问题:
如果i大于或等于1。