简体   繁体   中英

String index out of bounds exception java

I am getting the following error when calling a function from within my class: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 Although I used a system prints to see the inputs I am passing in the substring() function and everything seems to be right. The function isContained() returns a boolean value defining whether the substring passed as a parameter is in a list of words. My code is:

for(int i=0; i<=size; i++)
    for(int j=i+1; j<=size; j++)
        if(isContained(str.substring(i,j-i)))
            System.out.println(str.substring(i,j-i));

where size is the size of the string (str) I am passing in the function

You are calling str.substring(i, ji) which means substring(beginIndex, endIndex) , not substring(beginIndex, lengthOfNewString) .

One of assumption of this method is that endIndex is greater or equal beginIndex , if not length of new index will be negative and its value will be thrown in StringIndexOutOfBoundsException .

Maybe you should change your method do something like str.substring(i, j) ?


Also if size is length of your str then

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

should probably be

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

I think you need to change the looping condition which is the problem here. You are looping one more iteration when you do <=size and the index starts from i=0 . You can change this

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

to

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

and also take care about the inner loop condition.

IndexOutOfBoundsException -- if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Actually, your right edge of your substring function may be lower than the left one. For example, when i=(size-1) and j=size , you are going to compute substring(size-1, 1) . This is the cause of you error.

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