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;
    }
}

Leave a Comment