gpt4 book ai didi

java - 输出的第一部分(打印星星)不好

转载 作者:行者123 更新时间:2023-11-30 02:09:20 28 4
gpt4 key购买 nike

我正在做一项简单的任务,但我陷入困境...... output

我需要使第一行与其他所有内容保持一致,但无论我做什么,它都不想接受空格。那么,我应该纠正什么以及为什么?谢谢

public static String repeat(String s, int n) {
String res = "";

for (int i = 0; i < n; i++) {
res += s;

}
return res;
}

public static void main(String[] args) {

int n = 5;
for (int i = 0; i < n; i++) {

System.out.println(repeat("*", 5));
System.out.print(repeat(" ", n - i));

}
}

最佳答案

您需要在打印星星之前打印空格,因此请使用

System.out.print(repeat(" ", n - i));        
System.out.println(repeat("*", 5));

Online Demo

当前代码先打印星星,然后打印空格,因此问题是,星星的第一行永远不会受到空格的影响,因为它是在之后打印的

我建议使用 StringBuilder。

关于java - 输出的第一部分(打印星星)不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50555560/

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