Java Utility Library

Java Scanner - next() Method



The java.util.Scanner.next() method is used to find and return the next complete token from the scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

Syntax

public String next()

Parameters

No parameter is required.

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 is used to find and return the next complete token from the scanner.

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