Java Scanner hasNext() vs. hasNextLine():
That is, hasNext()
checks the input and returns true if it has another non-whitespace
character.
Whitespace
includes not only the space character, but also tab space (\t), line feed (\n), and even more characters.
Continuous whitespace characters are treated as a single delimiter.
System.in means Standard Input.
When you pass System.in to init the Scanner, it will read data from Standard Input.
And it will always waiting for the input unless your input is EOF
(Ctrl + Z in Windows
or Ctrl + D).
So the scanner will always waiting for a non-whitespace character from input.
Input
When you press Space Enter, it sends two whitespace character
\n
to the Standard Input, and the function scanner.hasNext()
is still waiting for a non-whitespace character. And scanner.hasNext()
doesn't return anything. That's why there is no output at this time.
Then you press c, it sends non-whitespace character c
to the Standard Input.
Output
Now your Standard Input contains
\n
c
, the third one is not a whitespace character.
Finally the function scanner.hasNext()
returns true.
Then the scanner.nextLine()
read a line till character \n
: it will be
(one character),
and program print
1
.
Standard Input now becomes c
, only one character,
which will cause scanner.hasNext()
to return true again:
Scanner will read a line, which will be one character c
,
and print c
1
.