2016-11-16 55 views
1

我想弄清楚如何读取文本文件中的字符串列表并返回找到的单词的位置。我不知道为什么这不起作用。有人能告诉我我做错了什么吗?它为每个单词返回-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"); 
+1

另外,删除你的else块或者你返回-1(除非“word”是第一个单词)。 –

+0

哦,是的,这是一个意外,我已经删除它,谢谢。 – iloveprogramming

回答

1

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

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

0

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