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

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
}

Leave a Comment