Java Scanner - hasNext() Method
The java.util.Scanner.hasNext() method returns true if the scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
Syntax
public boolean hasNext()
Parameters
No parameter is required.
Return Value
Returns true if this scanner has another token in its input.
Exception
Throws IllegalStateException, if this scanner is closed.
Example:
In the example below, the java.util.Scanner.hasNext() method is used to check whether the scanner has another token in its input or not.
import java.util.*; public class MyClass { public static void main(String[] args) { //String to scan String MyString = "Hello World 10 + 20 = 30.0"; //creating a Scanner Scanner MyScan = new Scanner(MyString); while(MyScan.hasNext()) { //print the next token while there is a next token System.out.println(MyScan.next()); } //close the scanner MyScan.close(); } }
The output of the above code will be:
Hello World 10 + 20 = 30.0
❮ Java.util - Scanner