我收到了以下代码:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
该代码的输出如下:
How many names are you going to save:3
Type a name: Type a name: John Doe
Type a name: John Lennon
注意它是如何跳过第一个名字的?它跳过它并直接进入第二个名称输入。我试过看是什么导致了这个,但我似乎无法指出它。我希望有一个人可以帮助我。感谢
答案 0 :(得分:26)
错误的原因是nextInt只拉取整数,而不是换行符。如果你在for循环之前添加一个in.nextLine(),它将占用空的新行并允许你输入3个名字。
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
in.nextLine();
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
或者只是读取该行并将该值解析为整数。
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine().trim());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
答案 1 :(得分:5)
使用sc.nextLine();两次,以便我们可以读取字符串的最后一行
sc.nextLine() sc.nextLine()
答案 2 :(得分:2)
这是因为in.nextInt()不会改变行。因此,首先“输入”(按3后)会导致循环中的in.nextLine()读取endOfLine。
您可以执行以下小改动:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
答案 3 :(得分:2)
这是因为in.nextInt()只接收一个int号,不接收新行。因此,您输入3并按“Enter”,行尾由in.nextline()读取。
这是我的代码:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}