Java Scanner类读取字符串

时间:2009-09-23 13:28:35

标签: java string class duplicates 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.next();
    }

    System.out.println(names[0]);

当我运行此代码时,扫描程序将只选取名字而不是姓氏。在尝试输入名称时有时会跳过一行,它会显示为我将名称留空并跳到下一个名称。我不知道是什么导致了这一点。

我希望有人可以帮助我!

编辑:我试过in.nextLine();它修复了完整的名称,但它仍然保持一行,这是输出的一个例子:

How many names are you going to save:  3
Type a name: Type a name: John Doe
Type a name: John Lennon

4 个答案:

答案 0 :(得分:8)

而不是:

in.next();

使用:

in.nextLine();

nextLine()读取字符,直到找到换行符'\n'

答案 1 :(得分:2)

Scanner.next在遇到分隔符时停止读取,分隔符是一个空格。请改用nextLine方法。

答案 2 :(得分:2)

在你的初始nextInt()之后,你的输入中仍然有一个空的换行符。所以只需在nextInt()之后添加一个nextLine(),然后进入你的循环:

...
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine(); // gets rid of the newline after number-of-names
names = new String[nnames];

for (int i = 0; i < names.length; i++){
    System.out.print("Type a name: ");
    names[i] = in.nextLine();
}
...

... Scanner in = new Scanner(System.in); nnames = in.nextInt(); in.nextLine(); // gets rid of the newline after number-of-names names = new String[nnames]; for (int i = 0; i < names.length; i++){ System.out.print("Type a name: "); names[i] = in.nextLine(); } ...

答案 3 :(得分:-1)

尝试使用:

System.out.println()

而不是:

System.out.print()