Home » Java programming language

Java Scanner findWithinHorizon() Method with Example

Scanner Class findWithinHorizon() method: Here, we are going to learn about the findWithinHorizon() method of Scanner Class with its syntax and example.
Submitted by Preeti Jain, on March 26, 2020

Scanner Class findWithinHorizon() method

Syntax:

    public String findWithinHorizon(Pattern patt, int horiz);
    public String findWithinHorizon(String patt, int horiz);
  • findWithinHorizon() method is available in java.util package.
  • findWithinHorizon(Pattern patt, int horiz) method is used to search the next occurrence of the given Pattern (patt) and it finds through the input up to the given horizon (horiz).
  • findWithinHorizon(String patt, int horiz) method is used to search the next occurrence of the pattern build from the given string (patt).
  • These methods may throw an exception at the time of searching the pattern.
    • IllegalStateException: This exception may throw when this Scanner is not opened.
    • IllegalArgumentException: This exception may throw when the given parameter horizon (horiz) is less than 0.
  • These are non-static methods, it is accessible with class object & if we try to access these methods with the class name then we will get an error.

Parameter(s):

  • In the first case, findWithinHorizon(Pattern patt, int horiz),
    • Pattern patt – represents the pattern to search for.
    • int horiz – represents the horizon.
  • In the second case, findWithinHorizon(String patt, int horiz),
    • String patt – represents the pattern defined by the given string to search for.
    • int horiz – represents the horizon.

Return value:

In both the cases, the return type of the method is String, it returns the message that meets the given pattern along with horizon.

Example:

// Java program to demonstrate the example
// of findWithinHorizin() method of Scanner

import java.util.*;
import java.util.regex.*;

public class FindWithinHorizon {
 public static void main(String[] args) {
  String str = "Java Programming! 3 * 8= 24";

  // Instantiates Scanner
  Scanner sc = new Scanner(str);

  // By using findWithinHorizon(Pattern,Horizon) method
  // is to find the next pattern from the given
  // Pattern ".ava" with horizon 5
  String pattern = sc.findWithinHorizon(Pattern.compile(".ava"), 5);
  System.out.println("sc.findWithinHorizon(Pattern.compile(.ava),5): " + pattern);

  // By using findWithinHorizon(String,Horzon) method
  // is to find the next pattern from the given
  // String "Java" with horizon 10
  pattern = sc.findWithinHorizon("Java", 10);
  System.out.println("sc.findWithinHorizon(Java,10): " + pattern);

  // Scanner closed
  sc.close();
 }
}

Output

sc.findWithinHorizon(Pattern.compile(.ava),5): Java
sc.findWithinHorizon(Java,10): null


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.