gpt4 book ai didi

java - 无法在 ArrayList 中找到匹配的字符串

转载 作者:行者123 更新时间:2023-12-02 05:33:08 26 4
gpt4 key购买 nike

这个想法很简单:

  1. 将文本文件加载到字符串中。
  2. 将此字符串拆分为段落。
  3. 将所有段落拆分为单词。
  4. 将每个单词添加到 ArrayList 中。

结果是一个包含文本文件中所有单词的 ArrayList。

该程序有效;它可以很好地加载 ArrayList 中的所有单词。

但是,任何在 ArrayList 中查找特定项目的“IF”语句都不起作用。

异常(exception):如果该单词是换行符。

public String loadText(String resourceName){


// Load the contents of a text file into a string
String text = "";
InputStream stream = FileIO.class.getResourceAsStream(resourceName);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String str = "";
try {
while ((str = reader.readLine())!=null){
text += str + "\n";
}
} catch (Exception e) {
System.out.println("Unable to load text stream!");
}
return text;
}

public void test(){

ArrayList<String> collectionOfWords = new ArrayList<String>();
String text = loadText("/assets/text/intro.txt");

// Split into paragraphs
String paragraphs[] = text.split("\n");
for (String paragraph: paragraphs){

// Split into words
String words[] = paragraph.split(" ");

// Add each word to the collection
for (String word: words){
collectionOfWords.add(word);
}

// Add a new line to separate the paragraphs
collectionOfWords.add("\n");
}

// Test the procedure using a manual iterator
for (int i=0; i<collectionOfWords.size(); i++){


// ===== WHY DOES THIS WORK?
if (collectionOfWords.get(i)=="\n")
System.out.println("Found it!");

// ===== BUT THIS DOESN'T WORK???
if (collectionOfWords.get(i)=="test")
System.out.println("Found it!");

// NOTE: Same problem if a I use:
// for (String word: collectionOfWords){
// if (word=="test")
// System.out.println("Found it!");
}
}

文本文件示例:快速布朗\n狐狸跳过\n测试这只懒狗\n

有什么想法吗?我现在只是从头开始我的设计并尝试一些完全不同的东西......

最佳答案

简短回答:使用 .equals 比较字符串,而不是 ==

长答案:

    // ===== WHY DOES THIS WORK?
if (collectionOfWords.get(i)=="\n")
System.out.println("Found it!");

这是可行的,因为你的程序中有两个"\n"。 (一个在 .add("\n") 中,另一个在 == "\n" 中。由于这两个字符串是程序中的文字,因此它们将引用同一个对象,即引用相等性检查(==)可以正常工作。

    // ===== BUT THIS DOESN'T WORK???
if (collectionOfWords.get(i)=="test")
System.out.println("Found it!");

您在文本文件中查找的单词在您的程序代码中不存在。 (它们不是文字。)这意味着从文件加载的字符串 "test" 和程序中的字符串文字 "test" 是两个不同的对象(尽管它们包含相同的值)。要测试两个不同的字符串是否包含相同的值,可以将它们与 equals 进行比较:

    if (collectionOfWords.get(i).equals("test"))
System.out.println("Found it!");

关于java - 无法在 ArrayList<String> 中找到匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25317640/

26 4 0