从文本文件线性搜索String数组中的单词

时间:2016-11-16 03:10:30

标签: java search recursion

我试图弄清楚如何在文本文件中读取字符串列表并返回找到的单词的位置。我不确定为什么这不起作用。有人能告诉我我做错了什么吗?它为每个单词返回-1,单词肯定在那里。

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");

2 个答案:

答案 0 :(得分:1)

您无法将字符串与words[i] == wordToFind进行比较。您必须使用words[i].equals(wordToFind)

您还应该删除for循环中的else块。

答案 1 :(得分:0)

你的循环在第一次迭代时返回。删除else块。