java.util.Scanner useDelimiter(Pattern pattern)

Description :

This java tutorial shows how to use the useDelimiter(Pattern pattern) method of Scanner class of java.util package. This method set the delimiter pattern to be used by the Scanner object.

Method Syntax :

public Scanner useDelimiter(Pattern pattern)

Parameter Input :

 

DataType Parameter Description
Pattern pattern The pattern to be used by the Scanner object

 

Method Returns :

This method simply returns this Scanner object.

Compatibility Version :

Requires Java 1.5 and up

Exception :

None

Discussion :

The useDelimiter(Pattern pattern) method sets the delimiter of the Scanner object.

Java Code Example :

This java example source code demonstrates the use of useDelimiter(Pattern pattern) method of Scanner class. Basically we have used the Pattern semicolon(;) to tokenize the String declared on the constructor of Scanner object.

There are three possible token on the String “Will Smith;Male;30” which is name,gender and age. The scanner class is used to tokenize the String and output the tokens in the console.

package com.javatutorialhq.java.tutorial.scanner;

import java.util.Scanner;
import java.util.regex.Pattern;

/*
 * This is a java example source code that shows how to use useDelimiter(Pattern)
 * method of Scanner class. We use the string ; as delimiter
 * to use in tokenizing a String input declared in Scanner constructor
 */

public class ScannerUseDelimiterDemo {

	public static void main(String[] args) {

		// Initialize Scanner object
		Scanner scan = new Scanner("Will Smith;Male;30");
		// initialize the delimiter patter
		scan.useDelimiter(Pattern.compile(";"));
		// Printing the delimiter used
		System.out.println("The delimiter used is "+scan.delimiter());
		// Printing the tokenized Strings
		while(scan.hasNext()){
			System.out.println(scan.next());
		}
		// closing the scanner stream
		scan.close();

	}

}

Sample Output :

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

java scanner usedelimiter(Pattern) method example

java scanner usedelimiter(Pattern) method example

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :