Java Scanner类读取字符串 [英] Java Scanner class reading strings
本文介绍了Java 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]);
当我运行此代码时,扫描仪只会拾取名字而不是姓氏。它有时会跳过一行,当尝试输入一个名称,它会显示,如果我把名称留空,并跳到下一个名字。我不知道是什么原因造成的。
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.
我希望有人能帮助我!
试试in.nextLine();它修复了完整的名称,但它仍然保持一行,这里是一个输出的示例:
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
推荐答案
而不是:
in.next();
使用:
in.nextLine();
nextLine()
读取字符找到一个新的字符'\\\
'
nextLine()
reads the characters until it finds a new line character '\n'
这篇关于Java Scanner类读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文