Scanner findAll(String) in Java

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

Syntax:

Stream<MatchResult> java.util.Scanner.findAll(String patString)

This method takes one argument. This method returns a stream of match results that match the provided pattern string.

Parameters: One parameter is required for this method.

patString: the pattern string.

Returns: a sequential stream of match results.

Throws:

1. NullPointerException - if patString is null.

2. IllegalStateException - if this scanner is closed.

3. PatternSyntaxException - if the regular expression's syntax is invalid

Approach 1: When no exception

Java

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.stream.Stream;

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

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

        String patString = "[a-z]";
        Stream<MatchResult> stream = scanner.findAll(patString);

        System.out.println(stream.count());

        scanner.close();
    }
}

Output:

8


Approach 2: NullPointerException 

Java

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.stream.Stream;

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

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

        String patString = null;
        Stream<MatchResult> stream = scanner.findAll(patString);

        System.out.println(stream.count());

        scanner.close();
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Scanner.findAll(Scanner.java:2938)


Approach 3: IllegalStateException 

Java

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.stream.Stream;

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

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

        String patString = "[a-z]";
        scanner.close();
        Stream<MatchResult> stream = scanner.findAll(patString);

        System.out.println(stream.count());

    }
}

Output:

Exception in thread "main" java.lang.IllegalStateException: Scanner closed at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150) at java.base/java.util.Scanner.findAll(Scanner.java:2939)


No comments:

Post a Comment