Scanner findInLine(String) in Java

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

Syntax:

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

This method takes one argument. This method attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.

Parameters: One parameter is required for this method.

pattern: a string specifying the pattern to search 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;

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

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

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

Output:

e


Approach 2: IllegalStateException

Java

import java.util.Scanner;

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

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

        String pattern = "[a-z]";
        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) at java.base/java.util.Scanner.findInLine(Scanner.java:1677)


No comments:

Post a Comment