テキストファイルの文字列のリストを読み込み、見つかった単語の位置を返す方法を理解しようとしています。なぜこれが動作していないのか分かりません。誰かが私が間違っていることを教えてもらえますか?それは各単語のために-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");
また、 'else'ブロックを削除するか、' word -1 'が最初の単語でない限り、 '-1'を返します。 –
ああ、それは事故で、私はすでにそれをおかげで削除しました。 – iloveprogramming