• Post Reply Bookmark Topic Watch Topic
  • New Topic

query on scanner.nextLine() method vs scanner.next() method  RSS feed

 
siva kumark
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why the below program is only taking n-1 inputs only? if i use sc.next() it takes n input? if i use sc.nextLine() it takes only n-1 inputs? please help.

 
Carey Brown
Saloon Keeper
Posts: 3309
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
rgsiva rgsivak wrote:why the below program is only taking n-1 inputs only? if i use sc.next() it takes n input? if i use sc.nextLine() it takes only n-1 inputs? please help.

This is one of the Scanner gotchas. When you do a nextXXX() of anything other than nextLine() it leaves a pending new-line in the queue. If you do another nextXXX() (anything other than nextLine()) it will skip over the new-line (if any) return the next chunk of data. nextLine() is the only method that flushes the new-line out of the queue. So when you're all done getting all the int's (or other types) that you want, call nextLine() once to flush and then again to get the actual line of text.

 
Campbell Ritchie
Marshal
Posts: 56521
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Carey Brown wrote:. . . This is one of the Scanner gotchas. When you do a nextXXX() of anything other than nextLine() it leaves a pending new-line in the queue. . . .
That is because the delimiter used defaults to multiple whitespace and line end sequences count as whitespace. So using the default delimiter is expected to leave the line end behind, and nextLine, as stated in the API correctly (but not stated correctly in any book I can remember) reads the remainder of the line from its current position.

And welcome to the Ranch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!