java.util.Scanner findWithinHorizon()

Description :

This java tutorial shows how to use the findWithinHorizon method of Scanner class of java.util package. This method returns a String that corresponds to the pattern specified as method argument. This method simply attempts to find the next occurrence of a pattern input ignoring delimiters.

Method Syntax :

There are two overloaded method of Scanner findWithinHorizon java method.

java scanner findwithinhorizon overloaded method
Overloaded methods are those method with same name but with different method signatures

Method 1 : 

public String findWithinHorizon(String pattern,int horizon)

Method 2:

public String findWithinHorizon(Pattern pattern,int horizon)

Parameter Input :


DataType Parameter Description
String Pattern a string specifying the pattern to search for
Pattern Pattern The pattern to search for by this Scanner
int horizon


Method Returns :

This method returns the String which satisfies the  pattern specified as method argument within the horizon. If the pattern was found, the Scanner object skipped the string that satisfies the pattern specified and returns the string that matched the pattern. If the pattern was not found, the scanner will return null and the position will not changed.

Compatibility Version :

Requires Java 1.5 and up

Exception :


Discussion :

Basically the two overloaded findWithinHorizon method do the same tasks. Mean to say that invoking findWithinHorizon(String pattern,int horizon) is the same as findWithinHorizon(Pattern.compile(String pattern),int horizon).

The horizon method argument signifies how many characters have to be taken out to satisfy the pattern specified.

Java Code Example :

This java example source code demonstrates the use of findWithinHorizon method of Scanner class.


 * Scanner findWithinHorizon java method example

import java.util.Scanner;

public class ScannerfindWithinHorizon {

	public static void main(String[] args) {
		// initialize scanner object
		Scanner scan = new Scanner("x12 14 16 100");
		// declare horizon
		int horizon = 8;
		// print the result of the findWithinHorizon
		System.out.println("Printing the string that satisifies the pattern within the horizon");
		System.out.println(scan.findWithinHorizon("[0-9].*", horizon));
		// close the scanner object



Sample Output :

Running the findWithinHorizon method example source code of Scanner class will give you the following output

Printing the string that satisifies the pattern within the horizon
12 14 1

Exception Scenario :


Similar Method :

  • N/A

Suggested Reading List :

References :