findWithinHorizon(String, int): This method is available in java.util.Scanner class of Java.
Syntax:
String java.util.Scanner.findWithinHorizon(String pattern, int horizon)
This method takes two arguments. This method attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
Parameters: Two parameters are required for this method.
pattern: a string specifying the pattern to search for.
horizon: the search horizon.
Returns: the text that matched the specified pattern.
Throws:
1. IllegalStateException - if this scanner is closed.
2. IllegalArgumentException - if the horizon is negative
Approach 1: When no exception
Java
import java.util.Scanner;public class ScannerfindWithinHorizon2 {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);String pattern = "[a-z]";int horizon = 1;System.out.println(scanner.findWithinHorizon(pattern,horizon));scanner.close();}}
Output:
null
Approach 2: IllegalStateException
Java
import java.util.Scanner;public class ScannerfindWithinHorizon2 {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);String pattern = "[a-z]";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) at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1746)
Approach 3: IllegalArgumentException
Java
import java.util.Scanner;public class ScannerfindWithinHorizon2 {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);String pattern = "[a-z]";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) at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1746)
No comments:
Post a Comment