Java Scanner useDelimiter()

In this guide, you will learn about the Scanner useDelimiter() method in Java programming and how to use it with an example.

1. Scanner useDelimiter() Method Overview

Definition:

The useDelimiter() method of the Scanner class in Java is used to set the delimiting pattern of the scanner which separates tokens in the input. It provides a way to instruct the scanner to recognize custom delimiters apart from whitespace, which is the default delimiter.

Syntax:

public Scanner useDelimiter(String pattern) 
public Scanner useDelimiter(Pattern pattern)

Parameters:

- pattern: A string specifying the delimiter pattern. This can be a regular expression.

- Alternatively, you can use the Pattern class to specify the delimiter.

Key Points:

- The useDelimiter() method returns a Scanner object, allowing for method chaining.

- The scanner will use the provided delimiter until it's changed again.

- If no delimiter is set, the default is whitespace.

- The delimiter does not need to be a single character; it can be a regular expression to match more complex patterns.

2. Scanner useDelimiter() Method Example

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        String data = "apple,orange-banana;grape";
        Scanner scanner = new Scanner(data).useDelimiter("[,-;]+");

        while(scanner.hasNext()) {
            String fruit = scanner.next();
            System.out.println(fruit);
        }
    }
}

Output:

apple
orange
banana
grape

Explanation:

In this example, we have a string of fruit names separated by different delimiters: comma, hyphen, and semicolon. We use the useDelimiter() method to specify a regular expression that matches any of these delimiters. The scanner then reads and prints each fruit name separately.

Comments