java - StringBuilder 在 Java 中追加到 for 循环中

标签 java for-loop stringbuilder

当我执行以下命令时:

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/

相关文章:

java - 使用Swing和Java, "Swing-Shell"线程做了什么

java - 为什么我的 ListView 不显示来自 SQLite 数据库的数据?

java - 使用 Intent 中传递的 arrayList 时出错

python - 具有多个变量的 For 循环 - Python

java - 在 Java 中,如何有效地从 ArrayList<StringBuilder> 中删除重复项?

java - 在 java 中使用多个 bufferedImages

java - for 循环中的数组

c - 是否每次都读取数组值作为循环停止条件?

c# - .NET 字符串和引用类型参数

android - 使用 StringBuilder 追加