Scanner findInLine(Pattern) in Java

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

Syntax:

String java.util.Scanner.findInLine(Pattern pattern)

This method takes one argument. This method attempts to find the next occurrence of the specified pattern ignoring delimiters.

Parameters: One parameter is required for this method.

pattern: the pattern to scan for.

Returns: the text that matched the specified pattern.

Throws:

IllegalStateException - if this scanner is closed

Approach 1: When no exception

Java

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

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

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

        String regex = "[a-z]";
        Pattern pattern = Pattern.compile(regex);
        System.out.println(scanner.findInLine(pattern));
        scanner.close();
    }
}

Output:

e


Approach 2: IllegalStateException

Java

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

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

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

        String regex = "[a-z]";
        Pattern pattern = Pattern.compile(regex);
        scanner.close();
        System.out.println(scanner.findInLine(pattern));

    }
}

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.findInLine(Scanner.java:1699)


No comments:

Post a Comment