java.lang.StringIndexOutOfBoundsException: String index out of range

后端 未结 3 1837
别跟我提以往
别跟我提以往 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:30

    This is the problem:

     for(int j1=0;j1<w.length();j1++,i1++)
    

    On each iteration through the loop, you're incrementing i1 as well as j1. i1 could already be at the end of s, so after you've incremented it, s.charAt(i1) is going to be invalid.

    Two asides:

    • You should look at String.regionMatches
    • Using consistent indentation and sensible whitespace can make your code much easier to read.
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-06 17:39

    A few tips:

    First, always include the full stack trace when you are asking for debugging help. It should point to the exact line number the issue is happening on.

    Second, your issue is likely in your most inner loop for(int j1=0;j1<w.length();j1++,i1++) you are incrementing i1 in addition to j1 this will cause i1 to eventually go beyond the size of String s

    Finally, you should consider using the String.contains() method for Strings or even a Regular Expression.

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