• Post Reply Bookmark Topic Watch Topic
  • New Topic

Confused by hasNext()  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am super new to java and programming, and I do not really understand how the hasNext() method works with while loops and System.in
Is the condition of the loop being checked retroactively? Also I'm really confused about why if I push [enter] on my keyboard about 5 times before inputting another character nothing happens, but when I enter a character such as "t" after those 5 times of pushing [enter] the while loop prints the count++ 5 times without having me input again (I put an example of what I mean at the bottom of this post). What is the mechanism for that?


Output (I entered a then b then c then I pushed [enter] five times before inputting "t"):
a
1
b
2
c
3




t
4
5
6
7
8
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
Did you enter abc or a b c? Or did you push enter between the three letters?

You know a Scanner defaults to using 1 or more whitespace characters as its delimiter? a b c counts as three tokens. Then whatever follows the c until you push return counts as the nextLine input. Beware: as you see here, nextLine can return an empty String, which counts as a line but not as a token.
So you have a as a new line followed the println() call which moves you to the next line, etc etc. You must have pushed the enter key after a. Your five enters do not count as tokens but they do count as next lines, so you go from 3 to 8. Your loop iterates until you get to t (because you now have a next token) by which time you have stored 5 blank lines.

Does your program terminate by itself? Or did you push ctrl‑D or ctrl‑Z to terminate the input?
 
John Sender
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

thanks I think I understand how this loop is operating. If there is no token ahead of the scanner, the hasNext() has the user input via the keyboard until they enter a token and a new line?
Yes, the program terminates via <Ctrl> + z.
Yes, I typed a [enter] b [enter] c [enter]

Thanks again
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome. I think the Scanner assumes there will be a next token until you enter ctrl‑Z. The loop therefore continues as its condition remains true.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!