罗马数字到整数转换器中的 ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException in Roman numeral to integer converter

我必须编写一个程序将罗马数字转换为相应的整数值,但我一直收到 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[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);

导致数组越界。你可以再次模拟for循环来检查这个索引

  char next_char = n1[i + 1];

你的 for 循环从 i = 0i = n1.length - 1,所以行

char next_char = n1[i + 1];

将始终导致 ArrayIndexOutOfBoundsException 异常。

wikipedia开始,罗马数字最多由三个独立的组组成:

  1. 男,MM,MMM;
  2. C、CC、CCC、CD、D、DC、DCC、DCCC、CM;
  3. X、XX、XXX、XL、L、LX、LXX、LXXX、XC;和
  4. 一、二、三、四、五、六、七、八、九。

建议大家分开解析。

其他人对原因的看法是正确的。我认为您可以将 next_char (根据命名约定应该是 nextChar)设置为一个虚拟值,该值与罗马数字中使用的任何字母都不匹配,以防没有任何字母下一个字符:

      char nextChar;
      if (i + 1 < n1.length) {
        nextChar = n1[i + 1];
      } else {
        nextChar = '[=10=]';
      }

通过此更改,您的程序打印:

Roman Numeral: 
CXIII
Number: 
113

Vitor SRG 也是正确的,您的程序缺乏验证,这是不好的。