当我执行以下操作时:
static void Append() {
StringBuilder sb = new StringBuilder();
System.out.print("How many words do you want to append? ");
int n = input.nextInt();
System.out.println("Please type the words you want to append: ");
for (int c = 1; c <= n; c++) {
String str = input.nextLine();
sb.append(str);
System.out.print(" ");
}
System.out.print(sb);
}
假设我输入 3,那么计算机只允许我输入 2 个单词。
这是输出:
How many words do you want to append? 3
Please type the words you want to append:
I
am
Iam
另外,为什么单词前有一个空格?打印功能在输入功能之后。那么不应该是相反的吗?
如果你调试那个程序,你会发现循环的第一次会得到input.nextLine()
一个空字符串。这是出现问题的时候。
当您输入 a3
和 a \n
for 时int n = input.nextInt();
,输入缓冲区包含“3\n”,并且input.nextInt();
只会取“3”,如下图所示:
其中position
输入为 1,缓冲区中剩余“\n”。然后当程序需要 时nextLine()
,它将读取缓冲区直到出现“\n”,这导致读取一个空字符串。
所以一个可能的解决方法是String empty = input.nextLine();
在循环之前添加一个,或者使用input.next();
而不是input.nextLine();
,因为在文档中说,input.next();
将返回下一个标记。
更新:请注意,没有人在底部回答您的第二个问题......
您应该System.out.println(" ");
将循环中的行修改为sb.append(" ");
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句