java for循环输出金字塔,在Java中使用嵌套的for循环打印金字塔形状的逻辑

I have modified sample code around to get the output I was looking for, but I do not understand the logic behind the nested for-loops below. Can someone explain to me in detail what each loop is doing and why is are the loops constructed in this way?

public class Pyramid {

public static void main(String[] args) {

int size = 15;

for (int i = 1; i <= size; i += 2) {

for (int k = 0; k < (7 - i / 2); k++) {

System.out.print(" ");

}

for (int j = 1; j <= i; j++) {

System.out.print("*");

}

System.out.println();

}

}

}

output (below):

*

***

*****

*******

*********

***********

*************

***************

解决方案

Nested for loops like that are used when you have pseudo code like this:

Do the following x times:

Do the following y times:

some stuff

Do the following z times:

some stuff

In your specific case, the size of the pyramid is dynamic and is stored in a variable called size. To print a pyramid, you have to print size times the following thing:

Some whitespace and some *

How do you print that then? You calculate how many white spaces and * should there be and print them. Since the numbers of whitespaces and * are dynamic, you need a for loop to do this, instead of hardcoding them in.

Do you see the structure now?

The outer loop prints each layer of the pyramid. The first inner loop prints the white spaces and the second inner loop prints the *.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值