gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:01:50 25 4
gpt4 key购买 nike

当我执行以下命令时:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com