I am trying to figure out how to read a list of Strings in a text file and return the position of the word found. I'm not sure why this isn't working. Can someone tell me what I'm doing wrong? It returns -1 for each word and the words are definitely in there.
public class LinearSearch extends SearchAlgorithm
{
public int search(String[] words, String wordToFind) throws ItemNotFoundException {
for (int i = 0; i < words.length; i++) {
if (words[i] == wordToFind) {
return i;
}
else {
return -1;
}
}
return -1;
}
public final static String FILE_AND_PATH = "longwords.txt";
/*
* TODO: Be sure to change the FILE_AND_PATH to point to your local
* copy of longwords.txt or a FileNotFoundException will result
*/
//Note how we deal with Java's Catch-or-Declare rule here by declaring the exceptions we might throw
public static void main(String[] args) throws FileNotFoundException {
File file = new File("/Users/myName/Desktop/compsci/HOMEWORK/recursion/longwords.txt");
Scanner input = new Scanner(file);
int wordCount = 0;
ArrayList<String> theWords = new ArrayList<String>();
//read in words, count them
while(input.hasNext()) {
theWords.add( input.next() );
wordCount++;
}
//make a standard array from an ArrayList
String[] wordsToSearch = new String[theWords.size()];
theWords.toArray(wordsToSearch);
//start with the linear searches
tryLinearSearch(wordsToSearch, "DISCIPLINES");
tryLinearSearch(wordsToSearch, "TRANSURANIUM");
tryLinearSearch(wordsToSearch, "HEURISTICALLY");
tryLinearSearch(wordsToSearch, "FOO");