Java Utility Library

Java Scanner - hasNext() Method



The java.util.Scanner.hasNext() method returns the next token if it matches the specified string. The scanner does not advance past any input.

Syntax

public boolean next(String pattern)

Parameters

pattern Specify a string specifying the pattern to scan.

Return Value

Returns true if the next token matches the specified pattern.

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 next token matches the specified string or not.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {

    //String to scan
    String MyString = "Hello Cello Hullo Hallo World Jello";

    //creating a Scanner
    Scanner MyScan = new Scanner(MyString);

    while(MyScan.hasNext()) {
      //print the next token if matches "Hello"
      if(MyScan.hasNext("Hello"))
        System.out.println(MyScan.next("Hello"));
      
      //print the next token if matches "World"
      else if(MyScan.hasNext("World"))
        System.out.println(MyScan.next("World"));      
      
      //else move to the next token
      else
        MyScan.next();
    }

    //close the scanner
    MyScan.close();
  }
}

The output of the above code will be:

Hello
World

❮ Java.util - Scanner