gpt4 book ai didi

java - 从文本文件中线性搜索字符串数组中的单词

转载 作者:行者123 更新时间:2023-11-30 07:02:43 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于java - 从文本文件中线性搜索字符串数组中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40623448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com