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

问题描述 投票:-1回答:3

我必须编写一个程序,将罗马数字转换为相应的整数值,但我不断收到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);
java arrays indexoutofboundsexception
3个回答
0
投票

其他人对事业是正确的。我想你可以将next_char(根据命名约定应该是nextChar)设置为一个虚拟值,在没有任何下一个char的情况下,它与罗马数字中使用的任何字母都不匹配:

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

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

Roman Numeral: 
CXIII
Number: 
113

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


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
投票

这导致数组超出界限。您可以再次模拟for循环以检查此索引

  char next_char = n1[i + 1];
© www.soinside.com 2019 - 2024. All rights reserved.