Java Scanner 类读取字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1466008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:38:24  来源:igfitidea点击:

Java Scanner class reading strings

javastringclassduplicatesjava.util.scanner

提问by marcoamorales

I got the following code:

我得到以下代码:

        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]);

When I run this code, the scanner will only pick up the first name and not the last name. And it will sometimes skip a line when trying to enter a name, it will show up as if I had left the name blank and skip to the next name. I don't know what's causing this.

当我运行此代码时,扫描仪将只选择名字而不是姓氏。它有时会在尝试输入名称时跳过一行,它会显示为好像我将名称留空并跳到下一个名称。我不知道是什么原因造成的。

I hope someone can help me!

我希望有一个人可以帮助我!

EDIT: I have tried in.nextLine(); it fixes the complete names but it still keeps a line, here is an example of the output:

编辑:我试过 in.nextLine(); 它修复了完整的名称,但仍保留一行,以下是输出示例:

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

回答by rogeriopvl

Instead of:

代替:

in.next();

Use:

利用:

in.nextLine();

nextLine()reads the characters until it finds a new line character '\n'

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

回答by CPerkins

After your initial nextInt(), there's still an empty newline in your input. So just add a nextLine() after your nextInt(), and then go into your loop:

在您最初的 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();
}
...

回答by Amarghosh

Scanner.nextstops reading when it encounters a delimiter, which is a whitespace. Use the nextLinemethod instead.

Scanner.next在遇到分隔符(空格)时停止读取。请改用该nextLine方法。

回答by user3542612

Try using:

尝试使用:

System.out.println()

Instead of:

代替:

System.out.print()