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

2022-09-01 05:48:39

我正在编写一个简单的程序,提示用户输入一些学生,然后要求用户输入每个学生的姓名和分数,以确定哪个学生的分数最高。

我已经编写了程序代码并进行了编译。第一行询问一些学生并等待输入。第二行应该询问学生姓名并等待输入,然后第三行应该打印并要求该学生的分数,并等待输入,但是在第二行打印之后,立即调用第三行(第二行不等待输入),然后当我尝试在第三行之后输入请求的信息时,我得到一个运行时错误。

如何调整代码,以便在打印第三行之前打印第二行并等待输入字符串?

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

答案 1

这就是为什么我不喜欢使用 a,因为这种行为。(一旦我了解了正在发生的事情,并感到很舒服,我就非常喜欢扫描仪)。Scanner

正在发生的事情是,首先调用完成用户输入学生数的行。为什么?因为只读取一个 int 并且不完成该行。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();

正如我已经提到的,我不喜欢使用扫描仪。我曾经做的是使用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;
    }
}

答案 2
    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();