black panda black panda - 1 month ago 9
Java Question

Scanner.skip documentation concerning delimiters

According to the javadoc for

, this method:


Skips input that matches the specified pattern, ignoring delimiters.


But I am confused as to what the phrase 'ignoring delimeters' means because the following code throws an exception using Java 7 in Eclipse:

import java.util.Scanner;

public class Example
{

public static void main(String [] args)
{
Scanner sc = new Scanner("Hello World! Here 55");
String piece = sc.next();

sc.skip("World"); // Line A throws NoSuchElementException, vs.
sc.skip("\\sWorld"); // Line B works!
sc.findInLine("World"); // Line C works!
}
}


It does not seem to ignore delimiters when skipping, as demonstrated by Line A. However Line C appears to work even though its documentation uses the same "ignoring delimiters" phrase. Am I unclear on their concept of "ignoring delimiters" in this case or is this an actual bug? What am I missing?

Answer

You left out the next sentence of the method's description which reads (emphasis mine):

This method will skip input if an anchored match of the specified pattern succeeds.

So Scanner is not so much "ignoring" the delimiter, but simply trying to match the specified regular expression without taking the delimiter into account. In other words, the space before World is not treated as a delimiter by skip(), but merely part of the input that it is trying to match against.

Comments