简体   繁体   中英

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. 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.
To print the whole line just use 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. If you want to count the results, write 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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