How to terminate Scanner when input is complete?

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

Leave a Comment