简体   繁体   English

搜索并显示Java中文本文档的结果

[英]Search, and display results from a text document in java

I'm trying to search a text document in Java for a user defined input, below is my current code. 我正在尝试在Java文本文档中搜索用户定义的输入,以下是我当前的代码。 All this code is doing is telling me that whatever I search is in the document but I'm puzzled on how to display the actual results. 所有这些代码所做的就是告诉我,无论我搜索的是文档中的什么,但是我都对如何显示实际结果感到困惑。 Any help will be much appreciated. 任何帮助都感激不尽。

String userSearch = ""; int val = 0;
while(!userSearch.matches("quit"))
{
    System.out.println("Enter the word to be searched for");
    Scanner input = new Scanner(System.in);
    Scanner file = new Scanner(new File("file.txt"));
    userSearch = input.next();

    while(file.hasNextLine())           
    {
        String line = file.nextLine();
        if(line.contains(userSearch))
        {
            System.out.println(line.contains(userSearch));
            val = 1;
            break;
        }
        else
        {
            val = 0;
            continue;
        }
}

Currently when you found something, you call 目前,当您发现某物时,您致电
System.out.println(line.contains(userSearch));
which as far as I know would print either "true" or "false" as String.contains(String) should return a boolean value. 据我所知将打印“ true”或“ false”为String.contains(String)应该返回一个布尔值。
To print the whole line just use System.out.println(line); 要打印整行,只需使用System.out.println(line);
Or what would you like to see instead? 还是您想看什么?

And I do not know what your val variable is for, but if it just says "result found" or "not found" you could use boolean. 而且我不知道您的val变量是做什么的,但是如果它只是说“ result found”或“ not found”,则可以使用布尔值。 If you want to count the results, write var++; 如果要计算结果,请编写var++; when it found something and nothing if the line does not contain the result. 当它发现某物时,如果该行不包含结果,则什么也没有。 It's not about your question, but maybe useful too. 这与您的问题无关,但也可能有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM