我需要创建一个数组,提示教授输入他们班上有多少学生。然后提示他们输入他们的名字,直到满足学生人数。我所拥有的显然是错的,但我希望有一些见解。
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++)
{
System.out.println("Enter the name of student " + (i+1) + " in your class. ");
studentName[i] = console.nextLine();
System.out.println("Student name entered: " + studentName[i]);
}
编辑:我改变了一些代码,主要是数组。使用for循环,我打算简单地让它遍历每个数字并为其分配学生名称。但是对于最后一行代码,它给我一个错误,说它是一个令人困惑的缩进。
编辑2:在自我校对我的问题和代码之后,我已经注意到了非常基本的错误并且处理了它们,但最后一个问题。现在,当代码工作时,当它要求我输入名称时,它会跳过学生1,将其留空然后移到学生2.如此屏幕截图所示http://puu.sh/8fl8e.png
答案 0 :(得分:1)
Scanner console = new Scanner (System.in);
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++){
System.out.println("Enter the name of student" + (i+1) + "in your class. ");
studentName[i] = console.next();
}
测试代码:
for (int i=0; i<studentName.length; i++){
System.out.println(studentName[i]);
}
编辑:第二次修改的答案: 使用
console.next();
而不是
console.nextLine();
答案 1 :(得分:0)
我猜studentName
应该是String,而不是double。也许您应该考虑利用Java是OO的事实? :)
答案 2 :(得分:0)
因为您将名称作为字符串类型的输入,但是您使用的是double(不可能存储字符串),并且您在for循环后也错过了括号。 改变
double [] studentName = new double [numberOfStudents];
到
String [] studentName = new String [numberOfStudents];
最终正确的代码:
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String[numberOfStudents];
for (int i=0; i< numberOfStudents; i++){
System.out.println("Enter the name of student" + (i+1) + "in your class. ");
studentName[i] = console.nextLine();
}
答案 3 :(得分:0)
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++)
{
System.out.println("Enter the name of student " + (i+1) + " in your class. ");
studentName[i] = console.nextLine();
System.out.println("Student name entered: " + studentName[i]);
}