• Post Reply Bookmark Topic Watch Topic
  • New Topic

Scanner class  RSS feed

 
Ravi Dagar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code is working fine..
System.out.println("enter your name:");
String name=sc.nextLine();
System.out.println("enter your age:");
int age=sc.nextInt();

But if i use it like this:
System.out.println("enter your age:");
int age=sc.nextInt();
System.out.println("enter your name:");
String name=sc.nextLine();
then its not taking the second input..
please help i'm stuck with this..
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ravi. Welcome to the Ranch!

One thing you need to be careful about with Scanner - nextLine() moves you onto the next line, but most of the other methods, including nextInt(), don't.

So in your second example, let's imagine you enter "21<return>Bob<return>".

nextInt() consumes the 21, but does not consume the <return>. nextLine() therefore reads everything up to the end of the current line - but since the Scanner is already waiting at the end of the current line it just reads an empty String. The next line that you've entered is still waiting to be read.

Does that make sense to you?
 
Ravi Dagar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mathew!
Thank you very much.I got it...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!