Java字符串扫描器输入不等待信息,直接移动到下一条语句。如何等待信息?

35
我正在编写一个简单的程序,提示用户输入学生人数,然后要求用户按顺序输入每个学生的姓名和分数,以确定哪个学生得了最高分。
我已经编写了程序代码并且成功编译。第一行要求输入学生数量并等待输入。 第二行应该要求输入学生姓名并等待输入,然后第三行应该打印并要求输入该学生的分数,并等待输入。但是在第二行打印后,第三行立即被调用(第二行不等待输入),然后当尝试输入请求的信息时出现运行时错误。
我该如何修改代码以便第二行先打印并等待输入字符串,再打印第三行?
import java.util.Scanner;

public class HighestScore {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the number of students: ");
        int numOfStudents = input.nextInt();

        System.out.print("Enter a student's name: ");
        String student1 = input.nextLine();

        System.out.print("Enter that student's score: ");
        int score1 = input.nextInt();

        for (int i = 0; i <= numOfStudents - 1; i++) {

            System.out.println("Enter a student's name: ");
            String student = input.nextLine();

            System.out.println("Enter that student's score: ");
            int score = input.nextInt();

            if (score > score1) {
            student1 = student;
            score1 = score;
            }
        }
        System.out.println("Top student " +
        student1 + "'s score is " + score1);
    }
}
3个回答

57

这就是为什么我不喜欢使用 Scanner 的原因之一(一旦我理解了正在发生的事情并感到舒适,我非常喜欢 Scanner)。

发生的情况是调用 nextLine() 首先完成用户输入学生人数的那一行。 为什么? 因为 nextInt() 只读取一个整数而不结束该行。

因此,添加额外的 readLine() 语句将解决此问题。

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();

就如我之前所提到的,我并不喜欢使用Scanner。我通常使用BufferedReader。虽然更费功夫,但是实际上正在发生的事情更加明显易懂。你的应用程序应该像这样:

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

这有意义...我一直在使用扫描仪,感到很烦恼。 - anshulkatta

17
    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();

3
哇,看起来这是糟糕的设计 - 如果你要求一个整数,并使用nextInteger()方法,扫描器将会给你这个整数,但它现在在其缓冲区中保留了一个换行符,因为用户必须按回车键提交该整数。所以如果你稍后想提示用户输入字符串,它将不会等待输入,而只会返回一个新的换行符。 你不能清除扫描器以避免这种问题...
我错过了什么吗?
亚当

你是不是想用 nextInt() - JGFMK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接