当我执行以下命令时:
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
还有,为什么单词前面有一个空格?打印函数位于输入函数之后。那么不应该是相反的吗?
最佳答案
您应该将 nextLine() 替换为 next()。
import java.util.Scanner;
public class Main
{
static void Append() {
Scanner input = new Scanner(System.in);
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: ");
String str = null;
for (int c = 0; c < n; c++) {
str = input.next();
sb.append(str +" " );
}
System.out.print(sb);
}
public static void main(String[] args) {
System.out.println("Hello World");
Append();
}
}
关于java - StringBuilder 在 Java 中追加到 for 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51276774/