Java异常:java.lang.StringIndexOutOfBoundsException

时间:2016-03-03 14:18:11

标签: java

每次尝试编译异常java.lang.StringIndexOutOfBoundsException时,代码都会出现问题。这是问题的代码我真的不知道我做错了什么。在代码中,我尝试使用某些条件拆分stringstring表示多项式。

int[] coef1= new int[20];
for(i=0;i<polinom.length()+1;i++){
    if(polinom.charAt(i)=='+' )
         c=polinom.charAt(i+1);
    else{
       if(polinom.charAt(i)=='^'){
            v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
            coef1[v]=Integer.parseInt(Character.toString(c));
            System.out.print(coef1[v]);

       }
    }
}
for(i=0;i<polinom.length()+1;i++){
    if(polinom.charAt(i)=='-' )
         c=polinom.charAt(i+1);
    else{
       if(polinom.charAt(i)=='^'){
            v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
            coef1[v]=-Integer.parseInt(Character.toString(c));
            System.out.print(coef1[v]);

        }
    }
}

例外情况if(polinom.charAt(i)=='+' )

3 个答案:

答案 0 :(得分:4)

只需替换所有

for(i=0;i<polinom.length()+1;i++){

for(i=0;i<polinom.length()-1;i++){

由于索引是从0开始的,并且您使用polinom.charAt(i+1)i+1永远不应该等于(也不大于)polinom.length

或者如果您希望能够测试直到字符串的最后一个字符(用于其他处理),您可以确保polinom.charAt(i+1)永远不会触发i == polinom.length() - 1,只需在处理之前添加测试你的东西:

for(i=0;i<polinom.length();i++){ // not using -1, looping to the end of the string
    if(polinom.charAt(i)=='+' && i < polinom.length() - 1) // checking that no exception will be thrown
        c=polinom.charAt(i+1);
    else{
       if(polinom.charAt(i)=='^' && i < polinom.length() - 1){ // same
           v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
           coef1[v]=-Integer.parseInt(Character.toString(c));
           System.out.print(coef1[v]);
        }
   }
}

答案 1 :(得分:0)

在第二行,您正在使用

for(i=0;i<polinom.length()+1;i++){

+1应为-1

答案 2 :(得分:0)

我认为变量polinom是一个字符串。

你的循环超出了字符串的结尾:

for(i=0;i<polinom.length()+1;i++)

应该是

for(i=0;i<polinom.length()-1;i++)