Why is hasNext() False, but hasNextLine() is True?

You have a single extra newline at the end of your file.

  • hasNextLine() checks to see if there is another linePattern in the buffer.
  • hasNext() checks to see if there is a parseable token in the buffer, as separated by the scanner’s delimiter.

Since the scanner’s delimiter is whitespace, and the linePattern is also white space, it is possible for there to be a linePattern in the buffer but no parseable tokens.

Typically, the most common way to deal with this issue by always calling nextLine() after parsing all the tokens (e.g. numbers) in each line of your text. You need to do this when using Scanner when reading a user’s input too from System.in. To advance the scanner past this whitespace delimiter, you must use scanner.nextLine() to clear the line delimiter. See: Using scanner.nextLine()


Appendix:

LinePattern is defined to be a Pattern that matches this:

private static final String LINE_SEPARATOR_PATTERN =
                                       "\r\n|[\n\r\u2028\u2029\u0085]";
private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$";

The default token delimiter is this Pattern:

private static Pattern WHITESPACE_PATTERN = Pattern.compile(
                                            "\\p{javaWhitespace}+");

Leave a Comment