• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Difficulty using printf command, java automatically moving to next line

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 68
3
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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. ^_^

 
Bartender
Posts: 3323
86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I do like that solution better! I'd use that instead ;)
 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic