• Post Reply Bookmark Topic Watch Topic
  • New Topic

code not running scanner nextLine after using scanner nextInt  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.JPG
[Thumbnail for java.JPG]
output screen of the above code
 
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have fallen into the trap most of us did when first using Scanner.

Calling nextInt() removes the next integer from the stream but does not remove the following newline character so your next call to nextLine() will immediately return an empty string. The solution is to call nextLine() after calling nextInt() if you know the remainder of that input is not required Then print your next question and call nextLine() to wait for the answer.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is another possible solution but it is more time‑consuming.
Write yourself a utility class and you can see a possible method here which returns the next line without its being empty. You will not however see the nasty mistake I made unless you read the whole of the thread.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!