我正在使用这些Scanner方法nextInt()并nextLine()阅读输入.
它看起来像这样:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
Run Code Online (Sandbox Code Playgroud)
问题是输入数值后,第一个input.nextLine()被跳过而第二个input.nextLine()被执行,所以我的输出如下所示:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and …Run Code Online (Sandbox Code Playgroud) 我正在编写一个简单的程序,提示用户输入一些学生,然后要求用户输入每个学生的姓名和分数,以确定哪个学生的分数最高.
我编写了程序代码并编译.第一行要求一些学生并等待输入.第二行应该是要求学生姓名并等待输入,然后第三行应该打印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 …Run Code Online (Sandbox Code Playgroud)