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 sys
You are calling str.substring(i, j-i)
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++)
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.
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.