在Java中使用嵌套的for循环打印金字塔形状的逻辑 [英] Logic behind printing pyramid shape using nested for loops in Java

查看:898
本文介绍了在Java中使用嵌套的for循环打印金字塔形状的逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经修改了示例代码以获得所需的输出,但是我不理解下面嵌套的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

在您的特定情况下,金字塔的大小是动态的,并存储在名为size的变量中.要打印金字塔,您必须打印size倍以下内容:

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:

  • 一些空格和一些*

那你怎么打印呢?您计算应该有多少空格和*并打印出来.由于空格和*的数量是动态的,因此您需要一个for循环来执行此操作,而不是对其进行硬编码.

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.

您现在看到结构了吗?

外部循环将打印金字塔的每一层.第一个内部循环打印空白,第二个内部循环打印*.

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

这篇关于在Java中使用嵌套的for循环打印金字塔形状的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆