Java Scanner class reading strings [duplicate]

佐手、 提交于 2019-12-30 10:23:26

问题


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:

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

回答1:


Instead of:

in.next();

Use:

in.nextLine();

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




回答2:


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:

...
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:


Scanner.next stops reading when it encounters a delimiter, which is a whitespace. Use the nextLine method instead.




回答4:


Try using:

System.out.println()

Instead of:

System.out.print()


来源:https://stackoverflow.com/questions/1466008/java-scanner-class-reading-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!