Scanner match() in Java

match(): This method is available in java.util.Scanner class of Java.

Syntax:

MatchResult java.util.Scanner.match()

This method returns the match result of the last scanning operation performed by this scanner.

Parameters: NA

Returns: a match result for the last match operation.

Throws:

IllegalStateException - If no match result is available

Approach 1: When no exception

Java

import java.util.Scanner;

public class Scannermatch {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);
        System.out.println(scanner.hasNext("Hello"));
        System.out.println(scanner.match());
        scanner.close();
    }
}

Output:

true

java.util.regex.Matcher$ImmutableMatchResult@22f71333


Approach 2: IllegalStateException 

Java

import java.util.Scanner;

public class Scannermatch {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        System.out.println(scanner.match());
        scanner.close();
    }
}

Output:

Exception in thread "main" java.lang.IllegalStateException: No match result available at java.base/java.util.Scanner.match(Scanner.java:1398)


No comments:

Post a Comment