看看以下代码:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();
String[] students = new String [numberOfStudents];
//input.nextLine();
for (int i = 0; i < students.length; i++){
System.out.println("Enter name for student " + (i+1) + ":" );
students[i] = input.nextLine();
}
for (int i = 0; i < students.length; i++){
System.out.println(students[i]);
}
}
}
你可以看到我注释掉了声明&#34; input.nextLine();&#34;就在第一个循环之前,如果我执行这个代码(这是我的原始代码),循环运行两次然后停止并等待我的输入,然后继续正常,所以为了解决这个问题我需要输入那个评论线然后它正常工作,每次迭代后停止并要求输入。为什么会这样,Scanner究竟是如何工作的?
示例输出:
没有input.nextLine();在循环之前:
Enter the number of students: 4
Enter name for student 1:
Enter name for student 2:
name1 name2
Enter name for student 3:
name3
Enter name for student 4:
name4
如果我取消注释input.nextLine();输出如下:
Enter the number of students: 4
Enter name for student 1:
name1
Enter name for student 2:
name2
Enter name for student 3:
name3
Enter name for student 4:
name4
现在它正常执行。
答案 0 :(得分:0)
在for循环中,您需要将input.nextLine();
替换为input.next();
,因为nextLine()
方法会将扫描程序前进到下一行并返回读取的内容,而next()
等待下一行输入。以下工作:
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();
String[] students = new String[numberOfStudents];
// input.nextLine();
for (int i = 0; i < students.length; i++) {
System.out.println("Enter name for student " + (i + 1) + ":");
students[i] = input.next();
}
for (int i = 0; i < students.length; i++) {
System.out.println(students[i]);
}