Java Scanner class reading strings [duplicate]

十年热恋 提交于 2019-12-01 06:50:12

Instead of:

in.next();

Use:

in.nextLine();

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

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

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

user3542612

Try using:

System.out.println()

Instead of:

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