Javastring扫描器input不等待信息,直接移动到下一个语句。 如何等待信息?

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

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

如何调整代码,以便在打印第三行之前,第二行打印并等待inputstring?

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

这就是为什么我 不喜欢使用Scanner ,因为这种行为。 (一旦我明白发生了什么,感觉舒服,我就喜欢Scanner)。

发生的事情是, nextLine()的调用首先完成用户input学生人数的行。 为什么? 因为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(); 

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

哇,看起来像不好的devise – 如果你要求一个整数和一个nextInteger()扫描仪会给你的整数,但它现在持有一个新的行字符在缓冲区中,因为用户必须按Enter键提交整数,所以如果你以后想提示用户input一个string,它不会等待input,只是给你一个新的行字符。 你不能清除扫描仪,以避免这种问题…

我错过了什么?

亚当