ArrayIndexOutOfBoundsException罗马数字到整数转换器

时间:2019-03-31 04:18:38

标签: java arrays indexoutofboundsexception

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

3 个答案:

答案 0 :(得分:0)

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

char next_char = n1[i + 1];

将始终导致ArrayIndexOutOfBoundsException异常。

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

  1. M,MM,MMM;
  2. C,CC,CCC,CD,D,DC,DCC,DCCC,CM;
  3. X,XX,XXX,XL,L,LX,LXX,LXXX,XC;和
  4. I,II,III,IV,V,VI,VII,VIII,IX。

我建议您分别解析它们。

答案 1 :(得分:0)

其他原因是正确的。我认为您可以将next_char(根据命名约定应为nextChar)设置为一个虚拟值,该虚拟值在没有任何罗马数字的情况下不匹配下一个字符:

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

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

Roman Numeral: 
CXIII
Number: 
113

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

答案 2 :(得分:-1)

这会导致数组超出范围。您可以再次模拟for循环以检查该索引

  char next_char = n1[i + 1];
相关问题