1

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");
iloveprogramming
  • 81
  • 1
  • 1
  • 8

2 Answers2

1

You can't compare Strings with words[i] == wordToFind. You have to use words[i].equals(wordToFind).

You also should remove the else block within the for loop.

badjr
  • 2,166
  • 3
  • 20
  • 31
0

Your loop is returning on the first iteration. Remove the else block.

The Pademelon
  • 835
  • 11
  • 29