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
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:
String.regionMatches
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.
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.