gpt4 book ai didi

java - 嵌套循环使字符居中

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:41 26 4
gpt4 key购买 nike

我正在尝试制作一棵树,如下所示:

  *
***
*****
===

我能够使树居中,但我似乎无法使树桩与树的其余部分居中。我不知道如何做到这一点,任何帮助将不胜感激!(树桩总是有三个等号)

        int height = 4;
int counter = 1;
int spaces = 20;
for (int row = 1; row <= height; row++){

for (int j = 1; j <= spaces; j++){
System.out.print(" ");
}

for (int j = 1; j <= counter; j++){
System.out.print("*");
}

System.out.println("");
counter += 2;
spaces--;


} // end of outer loop
for(int i=0; i<3; i++){
System.out.print("=");
}

最佳答案

public class A {

public static void main(String[] args) {

int height = Integer.parseInt(args[0]);
int counter = 1;
int spaces = height-1;
for (int row = 1; row <= height; row++){

for (int j = 1; j <= spaces; j++){
System.out.print(" ");
}

for (int j = 1; j <= counter; j++){
System.out.print("*");
}

System.out.println("");
counter += 2;
spaces--;
} // end of outer loop
counter-=2; // length of last line
for(int i=1; i<=counter/2-1; i++){
System.out.print(" ");
}
System.out.print("===");
}
}

观察到我们在第一行留下了等于(最后一行的长度)/2的空间,并且它不断减少1。我们可以通过算术级数找到最后一行的长度。

请注意 === 的中间 = 始终位于(最后一行的长度)/2+1 个字符上。因此我们必须在其前面添加空格直到两个字符,即(长度)/2-1。

关于java - 嵌套循环使字符居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23625196/

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