Java - 在不使用列表的情况下搜索文件

Java - Searching through a file without using a list

我正在尝试创建一个程序,让用户在文件中搜索特定单词,而无需创建数组并将文件的所有内容添加到其中(因此可以轻松移植和使用具有不同的文件大小等)。下面是我的代码:

package test2;

import java.io.InputStream;
import java.util.Scanner;
import javax.swing.JOptionPane;

/**
 *
 * @author Kafaka157
 */
public class Prep2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    InputStream stream = Prep1.class.getResourceAsStream("words.txt");
    Scanner scanner = new Scanner(stream);             

    while(scanner.hasNextLine()){

        String word = JOptionPane.showInputDialog("Input word to look for: ");

        if(word.equals(scanner.next().trim())){
            JOptionPane.showMessageDialog(null, word + " found"); // found
            break;
        }else{
            JOptionPane.showMessageDialog(null,word + " not found"); // not found
            break;
        }
    }
  }
}

以上是我的代码,我没有遇到任何构建错误或任何错误,但是它不会 return 在我知道文件中的单词上找到。它似乎在每个实例中都默认为 else,有什么帮助/想法我哪里出错了吗?非常感谢。

public static void main(String[] args) {
InputStream stream = Prep1.class.getResourceAsStream("words.txt");
Scanner scanner = new Scanner(stream);             
boolean wordFound = false;//initially set it to false

String word = JOptionPane.showInputDialog("Input word to look for: ");

while(scanner.hasNextLine()){

    if(word.equals(scanner.next().trim())){
 //after the loop would be a better place to show below notification
        //JOptionPane.showMessageDialog(null, word + " found"); // found

        wordFound = true;//make the flag as true and break out of the loop
        break;
    }/*else{
        JOptionPane.showMessageDialog(null,word + " not found"); // not found
        break;
    }*/
}
if(wordFound)
        JOptionPane.showMessageDialog(null, word + " found"); // found
else
        JOptionPane.showMessageDialog(null,word + " not found");

几乎不需要修改,应该可以。上面提供的评论应该可以达到目的。主要问题是您在检查第一个单词本身后就跳出了循环!