String index out of bounds? (Java, substring loop)

前端 未结 5 580
感情败类
感情败类 2021-01-20 17:26

This program I\'m making for a COSC course isn\'t compiling right, I keep getting the error:

Exception in thread \"main\" java.lang.StringIndexOutOfBoundsException:

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-20 18:18

    I think your loop condition should be count < input.length. Right now, the last iteration runs with count == length, so your substring call is given a start index after the last character in the string, which is illegal. These type of boundary errors are very common when writing such loops, so it's always good to double- and triple-check your loop conditions when you encounter a bug like this.

    Also, comparing strings with the == operator usually won't do what you want. That compares whether or not the two variables reference the same object. Instead, you want to test string1.equals(string2), which compares the contents of the two strings.

提交回复
热议问题