简体   繁体   中英

ArrayIndexOutOfBoundsException in Roman numeral to integer converter

I have to write a program that converts a roman numeral to its corresponding integer value but I keep getting a java.lang.ArrayIndexOutOfBoundsException error. Anytime I change something, then it outputs the wrong value. Can someone let me know where I'm going wrong?

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);

Your for loop goes from i = 0 to i = n1.length - 1 , so the line

char next_char = n1[i + 1];

will always cause an ArrayIndexOutOfBoundsException exception.

From wikipedia , Roman numerals are composed by up to three independent groups:

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

I advise you to parse them separately.

The others are correct about the cause. I think you can just set next_char (which according to the naming conventions should be nextChar ) to a dummy value that doesn't match any letter used in Roman numerals in the case that there isn't any next char:

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

With this change your program prints:

 Roman Numeral: CXIII Number: 113

Vitor SRG is also correct that your program is lacking validation, which is not good.

That causes array out of bounds . You can simulate the for loop again to check this index

  char next_char = n1[i + 1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM