为什么我得到这个例外? StringIndexOutOfBounds

时间:2016-05-05 04:31:23

标签: java java.util.scanner

import java.util.Scanner;
public class romanNumeral {
public String roman_Numeral; 
public int roman_NumeralLength, decimalValue = 0;

public romanNumeral() 
{
   retrieveInput();
   loopThroughString();
   System.out.println(decimalValue);
}
public void retrieveInput() 
{
    Scanner console = new Scanner(System.in);
    System.out.print("Enter roman numeral: \n");
    roman_Numeral = console.next();
    roman_Numeral = roman_Numeral.toUpperCase();
    roman_NumeralLength = roman_Numeral.length();

}
public void loopThroughString()
{
    for(int i=0;i<=roman_NumeralLength;i++) 
    {
        if(roman_Numeral.charAt(i) == 'M')
            decimalValue+=1000;
        else if(roman_Numeral.charAt(i) == 'D')
            decimalValue+=500;
        else if(roman_Numeral.charAt(i) == 'C')
            decimalValue+=100;
        else if(roman_Numeral.charAt(i) == 'L')
            decimalValue+=50;
        else if(roman_Numeral.charAt(i) == 'X')
            decimalValue+=10;
        else if(roman_Numeral.charAt(i) == 'V')
            decimalValue+=5;
        else if(roman_Numeral.charAt(i) == 'I')
            decimalValue+=1;



    }
}

public static void main(String[] args) {
    romanNumeral program = new romanNumeral();


}

}

这是抛出的错误

Enter roman numeral: 
M
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:    String index out of range: 1
at java.lang.String.charAt(String.java:646)
at romanNumeral.loopThroughString(romanNumeral.java:25)
at romanNumeral.<init>(romanNumeral.java:9)
at romanNumeral.main(romanNumeral.java:46)

罗马数字的十进制值为:

  1. M = 1000

  2. D = 500

  3. C = 100

  4. L = 50

  5. X = 10

  6. V = 5

  7. I = 1

  8. 任何人都可以帮忙吗?该程序的含义是从用户获取罗马数字而不是将其转换为十进制值。任何输入都非常感激:)....用try / catch包围来处理它处理的异常而不是输出正确的值....所以为什么我得到这个异常以及如何摆脱它?

4 个答案:

答案 0 :(得分:2)

这一行是你的问题。

 for(int i=0;i<=roman_NumeralLength;i++)

NumeralLength会给你字符串中的字符数。但是,最大的合法索引始终是length() - 1。

因此,您正在尝试访问String之外的字符,从而产生indexOutOfBounds,因为索引始终将0视为一个位置。

修复。

 for(int i=0;i<=roman_NumeralLength-1;i++)
 // Just insert (-1)...Or change the comparator to "<".
 //Both give you the same result

答案 1 :(得分:1)

你是一个超过你的字符串长度

for(int i=0;i<=roman_NumeralLength;i++) //less than or equals too

应该是

for(int i=0;i<roman_NumeralLength;i++) //less than

答案 2 :(得分:1)

从你的情况中删除等号。

for(int i=0;i<roman_NumeralLength;i++)

答案 3 :(得分:1)

你的循环控制变量(i)上升到ParentView - 这是一个越界索引(因为字符串/列表的最大索引是len - 1 - 记住第一个索引是0)。

请尝试使用- (id) initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if(self) { [self addSubview:self.addStarButton]; } return self; } 作为循环条件。

相关问题