• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difficulty using printf command, java automatically moving to next line  RSS feed

 
Mike Kaine
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey, beginner here. I'm learning about the printf command, and when I have it, it is not letting me ad an input. Here is my quick little program:


The first section works good, but when i move down to the second part it just automatically finishes without letting me enter a phrase. Thanks for the help.
 
Skye Antinozzi
Ranch Hand
Posts: 68
3
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A quick way to fix this problem would be to just instantiate a new Scanner object and assign it to the reference input that you have already created. ^_^

 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

The problem you are seeing is because calling nextDouble() retrieves the next double from the input but leaves the trailing newline marker (from pressing the ENTER key) and so when you call nextLine() it doesn't wait for input as there is a newline marker waiting to be handled and so you get an empty string. The trick is to call nextLine() to remove the newline from the scanner's buffer before requesting the user enter a new value.
 
Skye Antinozzi
Ranch Hand
Posts: 68
3
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do like that solution better! I'd use that instead ;)
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again

As Tony has suggested, the correct answer is to learn the vagaries of Scanner. That bit about nextLine() is poorly described in all the books I have read. I wrote more about it here.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!