Search code examples
javaloopswhile-loopinfinite-loop

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


I ran into an issue. Below is my code, which asks user for input and prints out what the user inputs one word at a time.

The problem is that the program never ends, and from my limited understanding, it seem to get stuck inside the while loop. Could anyone help me a little?

import java.util.Scanner;

public class Test{
   public static void main(String args[]){
      System.out.print("Enter your sentence: ");
      Scanner sc = new Scanner (System.in);
     
      while (sc.hasNext() == true ) {
        String s1 = sc.next();
        System.out.println(s1);
      }

      System.out.println("The loop has been ended"); // This somehow never get printed.
   }
}

Solution

  • 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
    }