String index out of bounds exception java

前端 未结 3 1474
逝去的感伤
逝去的感伤 2020-11-29 12:43

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

相关标签:
3条回答
  • 2020-11-29 13:34

    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++)
    
    0 讨论(0)
  • 2020-11-29 13:43

    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.

    0 讨论(0)
  • 2020-11-29 13:46

    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.

    0 讨论(0)
提交回复
热议问题