aspose file tools*
The moose likes Beginning Java and the fly likes Input Skipped Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Input Skipped" Watch "Input Skipped" New topic
Author

Input Skipped

Ashish K. Singh
Greenhorn

Joined: Jan 31, 2009
Posts: 5
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
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
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

Joined: Jan 31, 2009
Posts: 5
Thanks, i got it now. I'll keep that in my mind what you have suggested
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Input Skipped