Understanding the findWithinHorizon Scanner Method

I am trying to use and understand the Java Scanner#findWithinHorizon .

I wrote the following code snippet that uses this method, but I can’t understand how it works.

  private static void findWithinHorizon() { String string = "Balkrishan Nagpal --> 1111, 2222, 3333"; Pattern pattern = Pattern.compile("[0-9]+"); Scanner scanner = new Scanner(string); while (scanner.hasNext()) { System.out.println("scanner.findWithinHorizon(pattern) = " + scanner.findWithinHorizon(pattern, 26)); } } 

When I run the above method, I get the following output

 scanner.findWithinHorizon(pattern) = 1111 scanner.findWithinHorizon(pattern) = 2222 scanner.findWithinHorizon(pattern) = 3333 

but I expect the output will only contain

 scanner.findWithinHorizon(pattern) = 1111 

since I provided the horizon value as 26.

My understanding is that when looking for a matching result, the scanner will not go beyond index 26 in a row.

Can someone explain how this works?

+5
source share
1 answer

From JavaDoc, it behaves as expected:

This method searches through the input to the specified search horizon, ignoring the delimiters. If a pattern is found, the scanner moves past the input that matches and returns a string that matches the pattern. If such a pattern is not found, zero is returned and the scanner position remains unchanged. This method may block waiting for input matching the pattern.

The scanner will never search more than the horizon code points beyond the current position .

After successful search 1111 position moves immediately after this match. The next call to findWithinHorizon searches for a maximum of 26 characters after the first match.


scanner.hasNext() returns true if there is something else after the space, except for the current position. scanner.findWithinHorizon(pattern, 26) then searches for the next 26 characters for the pattern and returns it (while advancing the current position immediately after the match).

So, your code runs as follows:

  • Scanner creation: current position 0 .
  • scanner.hasNext() returns true, since the string contains not only spaces.
  • scanner.findWithinHorizon(pattern, 26) searches for a pattern in the position range from 0 to 26, finds 1111 at positions 22-25, sets a new position at 26, and returns 1111
  • scanner.hasNext() returns true since the line starting at position 26 contains more than spaces
  • scanner.findWithinHorizon(pattern, 26) searches for a pattern in a range of positions from 26 to 52, finds 2222 at positions 28-31, sets a new position at 32, and returns 2222
  • etc.
+9
source

Source: https://habr.com/ru/post/1258656/


All Articles