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.
   }
}
                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
}
                        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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With