Java String Scanner输入不等待信息,直接移动到下一个语句.如何等待信息?

use*_*064 26 java string java.util.scanner

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

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

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*aux 45

这就是我的原因 不喜欢使用a Scanner,因为这种行为.(一旦我理解了发生了什么,并对它感到舒服,我非常喜欢Scanner).

发生的事情是,呼叫nextLine()首先完成用户输入学生数量的行.为什么?因为nextInt()只读取一个int并且没有完成该行.

所以添加一个额外的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();
Run Code Online (Sandbox Code Playgroud)

正如我已经提到的,我不喜欢使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Pri*_*ley 15

    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();
Run Code Online (Sandbox Code Playgroud)