• Post Reply Bookmark Topic Watch Topic
  • New Topic

Scanner function output problem  RSS feed

 
Dean Johnson
Greenhorn
Posts: 3
Android Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I am new to JAVA. i was reading Head first and after reading several chapters i decided to write my own program. Well till now i dont know much how to take input from user in program. so i searched on net and found a method called Scanner like this: Scanner in = new Scanner(System.in); to take input. well here is my code i made a (silly!) program..

It is basically to take input from user about the title and author of number of books from user and than simply show it



program complied perfect but while running it skipped the first title input and bumped directly to author input... i have also attached the screen shot of the output now please help me what to do.
send.jpg
[Thumbnail for send.jpg]
output
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scanner#nextInt() [like some other Scanner methods] doesn't consume the newline, which is left in the scanner buffer and consumed by the next call to next() or nextLine().
 
Dean Johnson
Greenhorn
Posts: 3
Android Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so should i not use this method for taking input? sorry for troubling but i really want to get through this input thing. thanks.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dean Johnson wrote:so should i not use this method for taking input? sorry for troubling but i really want to get through this input thing. thanks.



There's no hard and fast rule here. You need to use the methods as they make sense. The nextInt() method doesn't consume the newline, so you have to take care of it. You can use nextLine() to get the integer, and parse the integer value from the line. Or you can use nextInt() to get the integer, and then use nextLine() to consume the extraneous newline. Either technique, and I am sure there are others. work here.

Henry
 
Dean Johnson
Greenhorn
Posts: 3
Android Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it... thanks. for helping...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!