How to terminate Scanner when input is complete?

public static void main(String[] args) {

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

                String line = scan.nextLine().toLowerCase();
                System.out.println(line);   
            }

        } finally {
            scan.close();
        }
    }

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);

and

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

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


Solution 1:

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 and Mac OS that is (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 is not a user-friendly way, and in many cases it would be dangerous.)


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. (See How do I compare strings in Java?)

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").

Solution 2:

String comparison is done using .equals() and not ==.

So, try scan.nextLine().equals("").