Java Scanner findWithinHorizon() Method

The findWithinHorizon() is a Java Scanner class method which is used to find the next occurance of a pattern. There is two different types of Java findWithinHorizon() method which can be differentiated depending on its parameter. These are:

  • Java Scanner findWithinHorizon(Pattern pattern, int horizon) Method
  • Java Scanner findWithinHorizon(String pattern, int horizon) Method

findWithinHorizon(Pattern pattern, int horizon) Method

This is an inbuilt method of Java Scanner class which is used to find the next occurrence of the specified pattern. This method searches through the input up to the specified search horizon, ignoring delimiters.

findWithinHorizon(String pattern, int horizon) Method

This is a Java Scanner class method which is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.

Syntax

Following is the declaration of findWithinHorizon() method:

Parameter

DataTypeParameterDescriptionRequired/Optional
inthorizonIt is the search horizonRequired
StringpatternIt is a string specifying the pattern to search forRequired
PatternpatternIt is the pattern to scan forRequired

Returns

The findWithinHorizon() method returns the text that matched the specified pattern.

Exceptions

IllegalStateException- This method throws exception if the innvocation is done after the scanner has been closed.

IllegalArgumentException- It thrown this exception if horizon is negative.

Compatibility Version

Java 1.5 and above

Example 1

Output:

Output = 1111
Output = 2222
Output = 3333

Example 2

Output:

Print the string that satisifies the pattern within the horizon-
Result: 12 13 1

Example 3

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)
	at myPackage.ScannerFindWithinHorizonExample3.main(ScannerFindWithinHorizonExample3.java:9)

Example 4

Output:

Enter your email address: [email protected]
Output:abhishek