我在这里有一个代码,该代码创建一个数组并以人们的名字列入其中。但是,第一个阵列未被记录。
Scanner newscan = new Scanner(System.in);
System.out.println("How many people in the group?");
int groupnum = newscan.nextInt();
String[] people = new String[groupnum];
System.out.println("Put in the names of the people in the group");
String name;
int i = 0;
do{
System.out.println("Input Name");
name = newscan.nextLine();
people[i] = name;
i++;
}while(i<groupnum);
控制台显示这样的结果:
How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew
我尝试使用Intellij上的调试器,它表明我在第一个数组中放置的任何值都被忽略并将其设置为" null值。
我不知道解决这个问题。如果您可以告诉我我的代码的哪一部分引起此问题以及如何解决该问题,这将非常有帮助。
将代码修改为:
int groupnum = newscan.nextInt();
newscan.nextLine();
String[] people = new String[groupnum];
记住newscan.nextint((;不是完成新线字符,这就是为什么代码不起作用以及为什么获得:
Input Name
Input Name
行两次
读取NextInt((方法后,新行将作为输入。为了避免使用扫描仪类Skip方法。
检查scanner.nextline((javadoc。它是返回线分隔符,来自nextInt((输入。您可以在周期之前使用它
int i = 0;
newscan.nextLine();
do{
System.out.println("Input Name");
name = newscan.nextLine();
people[i] = name;
i++;
}while(i<groupnum);
只需添加此行
newscan.nextLine();
此行下方
int groupnum = newscan.nextInt();