Java Utility Library

Java Scanner - hasNext() Method



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

Syntax

public boolean hasNext(Pattern pattern)

Parameters

pattern Specify the pattern to scan for.

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 pattern or not.

import java.util.*;

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

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

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

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

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

The output of the above code will be:

Hello
Cello
Jello

❮ Java.util - Scanner