Scanner findWithinHorizon(Pattern, int) in Java

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

Syntax:

String java.util.Scanner.findWithinHorizon(Pattern pattern, int horizon)

This method takes two arguments. This method attempts to find the next occurrence of the specified pattern.

This method searches through the input up to the specified search horizon, ignoring delimiters.

Parameters: Two parameters are required for this method.

pattern: the pattern to scan for.

horizon: the search horizon.

Returns: the text that matched the specified pattern.

Throws:

1. IllegalStateException - if this scanner is closed.

2. IllegalArgumentException - if horizon is negative

Approach 1: When no exception

Java

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

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

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

        String regex = "[a-z]";
        Pattern pattern = Pattern.compile(regex);
        int horizon = 1;
        System.out.println(scanner.findWithinHorizon(
pattern, horizon));
        scanner.close();
    }
}

Output:

null


Approach 2: IllegalStateException 

Java

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

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

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

        String regex = "[a-z]";
        Pattern pattern = Pattern.compile(regex);
        int horizon = 1;
        scanner.close();
        System.out.println(scanner.findWithinHorizon(
pattern, horizon));

    }
}

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.findWithinHorizon(Scanner.java:1781)



Approach 3: IllegalArgumentException

Java

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

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

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

        String regex = "[a-z]";
        Pattern pattern = Pattern.compile(regex);
        int horizon = -1;
        System.out.println(scanner.findWithinHorizon(
pattern, horizon));
        scanner.close();
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: horizon < 0 at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1785)


No comments:

Post a Comment