Java 扫描程序类读取字符串

2022-09-01 13:11:02

我得到了以下代码:

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

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


答案 1

错误的原因是 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();
}

答案 2

使用 sc.nextLine();两次,以便我们可以读取字符串的最后一行

sc.nextLine() sc.nextLine()