【问题标题】:ArrayIndexOutOfBoundsException in Roman numeral to integer converter罗马数字到整数转换器中的 ArrayIndexOutOfBoundsException
【发布时间】:2019-03-31 04:18:38
【问题描述】:

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


【解决方案1】:

其他人对原因的看法是正确的。我认为您可以将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】:

    您的for 循环从i = 0 变为i = n1.length - 1,所以这条线

    char next_char = n1[i + 1];
    

    总是会导致ArrayIndexOutOfBoundsException 异常。

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

    1. 男、女、男;
    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。

    我建议你分开解析。

    【讨论】:

      【解决方案3】:

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

        char next_char = n1[i + 1];
      

      【讨论】:

        猜你喜欢
        • 2023-01-10
        • 2019-03-04
        • 2019-01-09
        • 2011-10-25
        • 2023-01-17
        • 1970-01-01
        • 2012-10-09
        相关资源
        最近更新 更多