打印出金字塔图案 java,如何在Java中使用for循环在Java中打印倾斜的金字塔图案?...

I have been trying to print different patterns using for loop statement in java. And now I want to learn how to print the following pattern. It is basically an inclined pyramid type of pattern.

*

**

***

****

***

**

*

I tried to make it and I did get the right results but the problem is that I think that the way I did it is an inconvenient way of doing it. Here is the code:

for (int x = 1; x <= 4; x++) {

for (int y = 1; y <= x; y++) {

System.out.print("*");

}

System.out.println();

}

for (int x = 1; x <= 3; x++) {

for (int y = 3; y >= x; y--) {

System.out.print("*");

}

System.out.println();

}

解决方案

Your code produces the right output and it clear enough to me. The only suggestion I could make is to use a variable for the size of the pyramid instead of a hard-coded value.

You could write it in a more compact manner, only using 2 loops, like this:

int size = 7;

for (int row = 0; row < size; row++) {

for (int column = 0; column <= Math.min(size-1-row, row); column++) {

System.out.print("*");

}

System.out.println();

}

The idea here is that:

For each row of the pyramid (so the row goes from 0 to size excluded)

We need to determine how many asterisks to print. If we are in the upper-half of the pyramid, it is the equal to the row we're at. It we are in the lower-half of the pyramid, it is equal to size-1-row (decreasing with the row increasing). So the count of asterisk is the minimum of row and size-1-row: this is factored in a single statement using Math.min(size-1-row, row).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值