如何正确获取 java 中包含特定单词的每一行

how to properly get every line containing a specific word in java

我正在尝试编写一个程序来读取文件并检查包含特定单词的每一行,然后打印 it.if 没有一个应该打印“与您的搜索不匹配”。这是我到目前为止所得到的,而且我无法把它全部 together.after 我所有的眨眼和用 if 替换 while 或将第二个 if 语句放在外面同时,有时我输入什么并不重要,它总是说“与您的搜索不匹配”,有时它说 java.util.NoSuchElementException:找不到行。有时它会冻结,我搜索了一下,它说它是 cmd 中的错误或 something.any 帮助将不胜感激 我是 java 的新手,所以请给我任何建议,这将对我有所帮助和感激

System.out.println("search for book");
 
String search = scan.next();    
scan.nextLine();    

File file = new File("library.txt");
Scanner in = null;
in = new Scanner(file);
          
String line = in.nextLine();
while(in.hasNext()) {
    if(line.contains(search)) {
        System.out.println(line);
    }   
           
    if(!line.contains(search)) {
        System.out.println("no match for your search");
        System.exit(0);
    }
}

不提代码中的逻辑错误,您应该在循环外创建逻辑(布尔)变量并将其设置为 false。如果您遇到您的情况,请将其设置为 true。 在 while 循环之后,检查值。如果为假,则表示未找到任何行,您应该打印您的消息。

示例:

boolean foundAnything = false;
while(...) {
    ...
    if(condition) {
        foundAnything = true;
        ...
    }
    ...
}

// Nothing was found
if(!foundAnything) {
    ...
}

sometimes it doesn't matter what i enter it always says "no match for your search"

这里最大的问题是循环中的这一部分:

while(in.hasNext()) {
    if(line.contains(search)) {
        System.out.println(line);
    }   
           
    if(!line.contains(search)) {
        System.out.println("no match for your search");
        //HERE!!!
        System.exit(0);
    }
}

System.exit(0) 将停止程序并且不会执行任何其他操作。因此,如果在该行中未找到 search 单词,则程序结束。

sometimes it says java.util.NoSuchElementException: No line found

您在循环之前阅读了第一行,也许您有一个空文件。

File file = new File("library.txt");
Scanner in = null;
in = new Scanner(file);

//this reads the first line of the file
String line = in.nextLine();
while(//rest of code...

您可以通过以下方式克服这两个问题:

  • 只在循环中读取文件内容
  • 使用标志检查是否找到该词
  • 仅当找到单词或文件没有更多行时才停止循环
  • 在循环中,如果还没有找到这个词,就让它继续
  • 除非确实需要,否则避免使用 System#exit
  • 如果在循环后找不到单词,打印一条消息

考虑到这些建议,您的代码可以这样设计:

File file = new File("library.txt");
Scanner in = new Scanner(file);

//Use a flag to check if the word was found 
boolean found = false;

//Stop the loop only if the word was found OR if the file has no more lines
while (!found && in.hasNextLine()) {
    //Read the contents of the file only in the loop
    String line = in.nextLine();
    if (line.contains(search)) {
        found = true;
        System.out.println(line);
    }
    //In the loop, if the word is not found yet, just let it continue
}
//If after the loop the word was not found, print a message
if (!found) {
    System.out.println("no match for your search");
}

首先,您似乎跳过了第一行。其次,第二个if子句是多余的。

Boolean found=false;
while(in.hasNext()) {
    String line = in.nextLine();
    if(line.contains(search)) {
        System.out.println(line);
        found=true;
    }           
}

if(found==false) System.out.println("no match for your search");