为什么我无法对 name[0]
赋值使用for loop
?下面是我的代码。我的代码只接受名称数量减去用户输入的数量 1。例如用户想要输入 4 个名称,我的代码只接受 3 个名称并将它们分配给 name[1],name[2],name[3]
.
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("How many Students?");
int noOfStudents=input.nextInt();
String[] name= new String[noOfStudents];
System.out.println("Enter student names:");
for(int x=0; x!=name.length;x++){
name[x]=input.nextLine();
}
System.out.println("Names are:");
for(String names: name){
System.out.println(names);
}
}
}
最佳答案
获取整数输入后,使用 input.nextLine(); 清除“\n”(换行)字符
int noOfStudents=input.nextInt();
String[] name= new String[noOfStudents];
System.out.println("Enter student names:");
// Add this
input.nextLine() // Clear away the new line character following your integer input
关于java - 字符串数组无法在索引[0]上分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31018745/