java.lang.StringIndexOutOfBoundsException: String index out of range

后端 未结 3 1838
别跟我提以往
别跟我提以往 2021-01-06 16:56

Hi I wrote a java code to find longest word made of other words. My logic is to read the list of words from the text file and add each word into an array (In the text the wo

3条回答
  •  抹茶落季
    2021-01-06 17:38

    When you use string.charAt(x), you must check that it is not beyond string length. Documentation shows that you will get "IndexOutOfBoundsException if the index argument is negative or not less than the length of this string". And in your particular case, you are only validating in the loop that you are under w length, so it will fail.

    As SO already said, the loop runs only taking into account w length, so in case you have a shorter s, it will raise that exception. Check the condition so it goes up to the shorter string or rethink the process.

提交回复
热议问题