How to get out of while loop in java with Scanner method "hasNext" as condition?

When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:

String s1 = sc.next();
if (s1.equals("exit")) {
    break;
}

Break will get you out of the loop.


You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.

while(!s1.equals("exit") && sc.hasNext()) {
    // operate
}

If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":

while(sc.hasNext()) {
    String s1 = sc.next();
    if(s1.equals("exit")) {
        break;
    }
    //operate
}

Your condition is right (though you should drop the == true). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt).


The Scanner will continue to read until it finds an "end of file" condition.

As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.