[java] 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.
   }
}

This question is related to java loops while-loop infinite-loop

The answer is


it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer. the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD


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.


You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)


If you don't want to use an EOF character for this, you can use StringTokenizer :

import java.util.*;
public class Test{
   public static void main(){
      Scanner sc = new Scanner (System.in);
      System.out.print("Enter your sentence: ");
      String s=sc.nextLine();
      StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
      while (st.hasMoreTokens() ) {
        String s1 = st.nextToken();
        System.out.println(s1);
      }

      System.out.println("The loop has been ended");
   }
}

I had the same problem and I solved it by reading the full line from the console with one scanner object, and then parsing the resulting string using a second scanner object.

Scanner console = new Scanner(System.in);
System.out.println("Enter input here:");
String inputLine = console.nextLine();

Scanner input = new Scanner(inputLine);
List<String> arg = new ArrayList<>();

while (input.hasNext()) {
    arg.add(input.next().toLowerCase());
}

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).


Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.

  while (sc.hasNext())
  {    
    s1 = sc.next();
    System.out.println(s1);
    System.out.print("Enter your sentence: ");
  }

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to while-loop

While, Do While, For loops in Assembly Language (emu8086) MySQL Insert with While Loop Python loop to run for certain amount of seconds How to break a while loop from an if condition inside the while loop? How to find sum of several integers input by user using do/while, While statement or For statement Python: How to keep repeating a program until a specific input is obtained? Creating multiple objects with different names in a loop to store in an array list ORA-06502: PL/SQL: numeric or value error: character string buffer too small How to break out of a loop in Bash? for or while loop to do something n times

Examples related to infinite-loop

how do I create an infinite loop in JavaScript break statement in "if else" - java Endless loop in C/C++ How to run the Python program forever? How to get out of while loop in java with Scanner method "hasNext" as condition? Python - A keyboard command to stop infinite loop? How to create an infinite loop in Windows batch file? Which is the correct C# infinite loop, for (;;) or while (true)?