Ioana
Ioana

Reputation: 67

Java Exception: java.lang.StringIndexOutOfBoundsException

I have some problems with the code every time I try to compile the exception java.lang.StringIndexOutOfBoundsException appears. Here is the code with the problem I really don't know what I have done wrong. In the code I try to split a string using some conditions, the string represent a polynomial.

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

        }
    }
}

The exception is here if(polinom.charAt(i)=='+' )

Upvotes: 1

Views: 124

Answers (3)

xlecoustillier
xlecoustillier

Reputation: 16351

Just replace all your

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

with

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

As indices are 0-based and you use polinom.charAt(i+1), i+1 should never be equal (nor greater) than polinom.length.

Or if you want ot be able to test until the last character of you string (for other processing), you can ensure that polinom.charAt(i+1) gets never triggered if i == polinom.length() - 1, just add a test before processing your stuff:

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

Upvotes: 4

Robert Kock
Robert Kock

Reputation: 6018

I suppose the variable polinom is a String.

Your're looping beyond the end of the string:

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

It should be

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

Upvotes: 0

f1sh
f1sh

Reputation: 11934

In the second line here you are using

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

That +1 should be -1.

Upvotes: 0

Related Questions