java.util.Scanner next(String pattern)

Description :

This java tutorial shows how to use the next(String pattern) method of Scanner class of java.util package. This method returns the next token which the Scanner object determined using the String pattern declared as method argument.

Method Syntax :

public String next(String pattern)

Parameter Input :

[table]
DataType|Parameter|Description
String|pattern|This method argument tells the Scanner on which pattern to scan
[/table]

Method Returns :

This method simply returns the next token.

Compatibility Version :

Requires Java 1.5 and up

Exception :

None

Discussion :

The Scanner next(String pattern) method is usually used when we are interested at specific token patterns like if we want to get integers only. This method really helpful as well in catching invalid tokens.

I will not go deeper into discussing regular expressions thus we have limited the discussion only in basic pattern.

Java Code Example :

This java example source code demonstrates the use of next(String pattern) method of Scanner class. First we have declared the String to tokenize using the Scanner constructor. A string pattern was in place to list down the tokens consists of numbers only.

Sample Output :

Running the next(String pattern) method example source code of Scanner class will give you the following output

java scanner hasnext(pattern) method example

java scanner hasnext(pattern) method example

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :