Bhargav
Bhargav

Reputation: 227

Specific String Produces StringOutOfBoundsException

My Program seems to Produce an String Index out of Range Error only for this Particular Input. The same code is working for other inputs. Will add the Output Screenshot and Code Below. I searched around - The fact that this error turns up only for a Single Input makes it tough to solve.

               int ind,len,vallen,amount,credits = 0;
               String credit; 
               String value,item;
               float oneamount;
              // System.out.println("Credit Assignment");
               ind=input.indexOf("is");
               credit = input.substring(0, ind-1);
           //       System.out.println(credit);
                 //Seperate the Quantity and Item Name from the String
                  len = credit.length();
                  vallen= credit.lastIndexOf(" ");
                  value= credit.substring(0,vallen);          //**Line 59**
                  item = credit.substring(vallen,len).trim();
                  System.out.println(value);

enter image description here

Upvotes: 0

Views: 118

Answers (3)

Bhargav
Bhargav

Reputation: 227

The Problem was with

ind=input.indexOf("is");

This returned 1 as Pish contained the String "is". So now I used

ind=input.lastIndexOf("is");

And the code is working fine. Thanks for the responses. Am a beginner. Will Format my code better and Include Stack Trace instead of Screenshots in the future.

Upvotes: 0

Volune
Volune

Reputation: 4339

Crash with pish pish Gold is 40 Credits

I guess the search returns the index of 1 because "pish" contains "is". Right ?

Right. ind is 1, credit is an empty string, and since no space can be found, vallen is -1 and the exception occurs on the next line.

Upvotes: 1

stinepike
stinepike

Reputation: 54682

String.lastIndexOf returns -1 if the specific search string is not found.

so in the following line

vallen= credit.lastIndexOf(" ");

if credit doesn't contains " " then vallen will be -1.

so

value= credit.substring(0,vallen); will throw error.

Upvotes: 1

Related Questions