user2318175 user2318175 - 4 months ago 28x
Java Question

How to terminate Scanner when input is complete?

public static void main(String[] args) {

Scanner scan = new Scanner(;
try {
while (scan.hasNextLine()){

String line = scan.nextLine().toLowerCase();

} finally {

Just wondering how I can terminate the program after I have completed entering the inputs?
As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs...
I tried:

if (scan.nextLine() == null) System.exit(0);


if (scan.nextLine() == "") System.exit(0);

They did not work.... The program continues and messes with the original intention,


The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.

There are two ways that the user could do this:

  • Enter an "end of file" marker. On UNIX that's (typically) CTRL+D, and on Windows CTRL+Z. That will result in hasNextLine() returning false.

  • Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.

(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that's not a user-friendly way to do this.)

The reason your current version is failing is that you are using == to test for an empty String. You should use either the equals or isEmpty methods.

Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").