Java String Scanner input does not wait for info, moves directly to next statement. How to wait for info? [duplicate]
That's why I don't didn't like using a Scanner
, because of this behavior. (Once I understood what was happening, and felt comfortable with it, I like Scanner a lot).
What is happening is that the call to nextLine()
first finishes the line where the user enters the number of students. Why? Because nextInt()
reads only one int and does not finish the line.
So adding an extra readLine()
statement would solve this problem.
System.out.print("Enter the number of students: ");
int numOfStudents = input.nextInt();
// Skip the newline
input.nextLine();
System.out.print("Enter a student's name: ");
String student1 = input.nextLine();
As I already mentioned, I didn't like using Scanner. What I used to do was to use a BufferedReader. It's more work, but it's slightly more straightforward what is actually happening. Your application would look like this:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of students: ");
int numOfStudents = Integer.parseInt(input.readLine());
String topStudent = null;
int topScore = 0;
for (int i = 0; i < numOfStudents; ++i)
{
System.out.print("Enter the name of student " + (i + 1) + ": ");
String student = input.nextLine();
// Check if this student did better than the previous top student
if (score > topScore)
{
topScore = score;
topStudent = student;
}
}
System.out.print("Enter the number of students: ");
int numOfStudents = input.nextInt();
// Eat the new line
input.nextLine();
System.out.print("Enter a student's name: ");
String student1 = input.nextLine();
Wow that looks like bad design - if you ask for an integer an d do a nextInteger() the scanner will give you the integer, but it is now holding a new line character in its buffer as the user has to press enter to submit the integer, so if you later want to prompt the user for a string it will not wait for input and just give you back a new line character. You cant clear the scanner to avoid this sort of problem...
What am I missing?
Adam