• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Input Skipped

 
Ashish K. Singh
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
class ScannerTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your Roll No.");
int rno = in.nextInt();
System.out.print("\nEnter your Full Name:");
String name =in.nextLine();

System.out.print("Enter percentage:");
double per = in.nextDouble();
System.out.println("\n\n\nHere is the info : ");
System.out.println("\nName:"+name+"\nRoll No."+rno+"\nPercentage : "+per);
}
}

In this code, when i execute it. The line(in bolds) which asked to enter NAme is skipped. Can anyone tell me why this is happening ? Thanks
 
Henry Wong
author
Marshal
Pie
Posts: 21423
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this code, when i execute it. The line(in bolds) which asked to enter NAme is skipped. Can anyone tell me why this is happening ?



It is "skipped" because the nextInt() method doesn't digest the CR (carriage return). So the call to the nextLine() method will take the CR (along with nothing before it) -- yielding a blank input for the name.

Henry
 
Campbell Ritchie
Sheriff
Pie
Posts: 49823
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch
Please maintain indentation and use the code button; your code is difficult to read. Don't put tags inside code; it won't compile with bold tags in.

Scanner takes some getting used to. You are reading the next int, and everybody would enter a return. Then when you read the next line you get a blank line, then when you put your name in the Scanner is already ahead of you and expects the percentage. You may need to discard lines every now and then with Scanner by calling nextLine(), or you can use the next() method and a different delimiter (see the Pattern class for a list of characters which represent new lines).
 
Ashish K. Singh
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, i got it now. I'll keep that in my mind what you have suggested
 
Campbell Ritchie
Sheriff
Pie
Posts: 49823
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic