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 :

 

DataType Parameter Description
String pattern This method argument tells the Scanner on which pattern to scan

 

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.

package com.javatutorialhq.java.tutorial.scanner;

import java.util.Scanner;

/*
 * This is a java example source code that shows how to use
 * next(String pattern) method of Scanner class.
 * Split the string into integer tokens
 */

public class ScannerNextStringPatternDemo {

	public static void main(String[] args) {

		// Initialize Scanner object
		Scanner scan = new Scanner("12 3 55 123");
		// intialize the String pattern
		String pattern = "[0-9]*";
		// Printing the tokenized Strings
		while(scan.hasNext()){
			System.out.println(scan.next(pattern));
		}
		// closing the scanner stream
		scan.close();

	}

}

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 :