Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am a beginner at java programming and has run into a strange 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 the program never ends, and from my limited understanding, it seem to have stuck inside the while loop. Could anyone help me a little? Thanks in advance.

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.
   }
}
like image 682
davidx1 Avatar asked May 07 '12 23:05

davidx1


3 Answers

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
}
like image 196
İsmet Alkan Avatar answered Oct 29 '22 03:10

İsmet Alkan


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.

like image 33
Alnitak Avatar answered Oct 29 '22 02:10

Alnitak


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.

like image 23
Renato Avatar answered Oct 29 '22 03:10

Renato