When my program enters this section of my code it crashes and produces this error
public static boolean Search(ArrayList<String> ArrayToSearch,String word)
{
String temp;
boolean found = false;
for(int counter = 0;found || counter < ArrayToSearch.size();counter++)
{
temp = ArrayToSearch.get(counter);
if(temp.equals(word.toLowerCase()))
{
found = true;
position = counter;
}
}
return found;
}
ArrayToSearch
are different array lists containing a single word per line which represents a dictionary. Word is the word the user wants searched for. This is the error it produces. Add is a method which calls this method and receives back a boolean from it
D:\>java Evan
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 109680, Size: 109680
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Evan.Search(Evan.java:95)
at Evan.Add(Evan.java:68)
at Evan.main(Evan.java:53)
D:\>
This is the problem:
found || counter < ArrayToSearch.size()
If found
ever becomes true, that will continue forever - or rather, until it goes bang because of this exception. I suspect you meant
!found && counter < ArrayToSearch.size()
In other words: "keep going while we haven't found the word and there's still more of the collection to look through."
However, it would be much clearer just to return directly as soon as you find the result. It would also be simpler if you used an enhanced for loop:
// Names change to follow conventions
public static boolean search(List<String> list, String word) {
// TODO: Handle the possibility of anything being null
for (String candidate : list) {
if (candidate.equals(word)) {
return true;
}
}
return false;
}
Or even more simply, just use List.contains
which does this already.
See more on this question at Stackoverflow