Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Scanner seeing "" as input with each loop  RSS feed

 
James Brooks
Gunslinger
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

I have a loop in which I read input from the keyboard with a scanner. Now, the problem is that with each loop, "" is seen by the Scanner and it makes a decision based on that input. Why is this? I've gotten around the problem with:


Am I correct in 'compensating' in this way, or is there some better wisdom someone can share with me here?

Thanks as always!
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could potentially use next() instead of nextLine(), if you don't care about ignoring input made up of N*javaWhitespace characters, if you're using Scanner's default delimiter: \p{javaWhitespace}+

java.util.Scanner#next() wrote:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.


Though, you'd be limited to input that doesn't contain any whitespace characters, so I'm not sure how usefull that'd be.
 
Campbell Ritchie
Marshal
Posts: 55681
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That sort of thing causes no end of confusion with Scanner. As you will see here, other people have similar problems. If you need the next line, then I think your original solution is good.

You could use this (or similar) instead of the if

I don't like while (true) myself, but this is a point there is by no means a consensus amongst Ranch users. I suggest a different idiom which Janeice delVecchio explains nicely here.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!