gpt4 book ai didi

java - 像半球一样在java中打印图案

转载 作者:行者123 更新时间:2023-11-30 06:01:07 24 4
gpt4 key购买 nike

尝试打印像下面的半球体这样的图案,我已经添加了实际输出和预期输出以及我的代码,任何人都可以帮助如何做到这一点。提前致谢

我的代码

public class PatternHalfSphere {

public static void main(String[] args) {
int i,j;
for(i = 1;i<=4;i++){
System.out.println();
for(int k=3;k>=i;k--){
System.out.print(" "+"*"+" ");
}
for(j=1;j<=i;j++){

System.out.print(" ");
}
}
for(int k=0;k<=3;k++) {
for(int l = 0; l<k;l++)
{
System.out.print(" "+"*"+" ");
}
System.out.println();
}
}


}

实际输出

 *  *  *    
* *
*

*
* *
* * *

预期输出

     *  *  *    
* *
*
* *
* * *

最佳答案

这个答案采用您的确切代码,并进行一些更改即可达到您期望的输出。您已经很接近了,只需在每行上打印一个分隔符,并从第二个外部 for 循环中删除一次迭代,以避免打印 * 两次。

for (int i=1;i <= 3; i++) {
for (int k=3; k >= i; k--) {
// print a new spacer at the start of each line
if (k == 3) System.out.print(" ");
System.out.print(" " + "*" + " ");
}
for (int j=1; j <= i; j++) {
System.out.print(" ");
}
System.out.println();
}

// start at k=2 so as to NOT print a double single asterisk *
for (int k=2; k <= 3; k++) {
for (int l=0; l < k; l++) {
// print a new spacer at the start of each line
if (l == 0) System.out.print(" ");
System.out.print(" "+"*"+" ");
}
System.out.println();
}

* * *
* *
*
* *
* * *

Demo

关于java - 像半球一样在java中打印图案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52260526/

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