Java Utility Library

Java Scanner - next() Method



The java.util.Scanner.next() method returns the next token if it matches the specified pattern. The method may block while waiting for input to scan, even if a previous invocation of hasNext(Pattern) returned true. If the match is successful, the scanner advances past the input that matched the pattern.

Syntax

public String next(Pattern pattern)

Parameters

pattern Specify the pattern to scan for.

Return Value

Returns the next token.

Exception

  • Throws NoSuchElementException, if no more tokens are available.
  • Throws IllegalStateException, if this scanner is closed.

Example:

In the example below, the java.util.Scanner.next() method returns the next token if it matches the specified pattern.

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