StringBuilder 在 Java 中追加 for 循环

StringBuilder append in for loop in Java

当我执行以下命令时:

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

还有,为什么前面有个space?打印功能在输入功能之后。那不是应该相反吗?

您应该将 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();
}
}

如果你调试那个程序,你会发现第一次循环会得到一个空字符串的input.nextLine()。这是问题出现的时候。

当您为 int n = input.nextInt(); 输入 3\n 时,输入缓冲区包含“3\n”,而 input.nextInt(); 将只接受它“3”,如下图:

其中输入的 position 为 1,缓冲区中保留“\n”。然后当程序需要 nextLine() 时,它会读取缓冲区直到一个“\n”,结果读取一个空字符串。

所以一个可能的解决方法是在循环之前添加一个 String empty = input.nextLine();,或者使用 input.next(); 而不是 input.nextLine();,因为在文档中说,input.next(); 将 return下一个标记。

更新:注意没有人回答你在底部的第二个问题...

您应该将循环中的行 System.out.println(" "); 修改为 sb.append(" ");

我认为是因为它读取了一行将字符更改为字符串 因此它将更改行视为第一行,并采用第一个字符串。 你只能输入两个字符串

如果你把从输入读取的代码打印行如下:

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: ");

  for (int c = 1; c <= n; c++) {
    String str = input.nextLine();
    System.out.println("input str=" + str); //pay attention to this line
    sb.append(str);
    System.out.print(" ");
  }
  System.out.print(sb);
}

您会看到第一次迭代不会从输入中读取。因为缓冲区中已经有 \n 是用 nextInt 读取的。

为了解决您可以在 nextInt 之后跳过一行的问题,如下面的代码(我不确定这是最佳解决方案):

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: ");

  if (input.hasNextLine()) input.nextLine();

  for (int c = 1; c <= n; c++) {
    String str = input.nextLine();
    System.out.println("input str=" + str);
    sb.append(str);
    System.out.print(" ");
  }
  System.out.print(sb);
}

如果您想将句子作为单个字符串读取,则使用 next() 不是解决方案。