How to test for blank line with Java Scanner?

后端 未结 5 1323
难免孤独
难免孤独 2020-12-02 23:58

I am expecting input with the scanner until there is nothing (i.e. when user enters a blank line). How do I achieve this?

I tried:

while (scanner.ha         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-03 00:31

    The problem with the suggestions to use scanner.nextLine() is that it actually returns the next line as a String. That means that any text that is there gets consumed. If you are interested in scanning the contents of that line… well, too bad! You would have to parse the contents of the returned String yourself.

    A better way would be to use

    while (scanner.findInLine("(?=\\S)") != null) {
        // Process the line here…
        …
    
        // After processing this line, advance to the next line (unless at EOF)
        if (scanner.hasNextLine()) {
            scanner.nextLine();
        } else {
            break;
        }
    }
    

    Since (?=\S) is a zero-width lookahead assertion, it will never consume any input. If it finds any non-whitespace text in the current line, it will execute the loop body.

    You could omit the else break; if you are certain that the loop body will have consumed all non-whitespace text in that line already.

提交回复
热议问题