Java Scanner 类读取字符串

2022-01-10 00:00:00 string duplicates java java.util.scanner

我得到以下代码:

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

注意它是如何跳过名字条目的?它跳过它,直接进入第二个名称条目.我已经尝试寻找导致这种情况的原因,但我似乎无法确定它.我希望有一个人可以帮助我.谢谢

Notice how it skipped the first name entry?? It skipped it and went straight for the second name entry. I have tried looking what causes this but I don't seem to be able to nail it. I hope someone can help me. Thanks

推荐答案

报错原因是nextInt只拉取整数,没有拉取换行符.如果你在你的 for 循环之前添加一个 in.nextLine(),它会吃掉新的空行并允许你输入 3 个名字.

The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.

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();
}

或者只是读取该行并将值解析为整数.

or just read the line and parse the value as an Integer.

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();
}

相关文章