解释在Java中创建一个金字塔

解释在Java中创建一个金字塔

本文介绍了解释在Java中创建一个金字塔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在初学java编程类,目前正在审查循环。如果有一件事我只是不明白,那就是金字塔。我已经在网上研究了这本书的练习,找到了金字塔例子的解决方案,但是即使看了代码,我仍然不明白,如果我的生活依赖于它,也不能重现答案。

下面是一个金字塔示例以及创建它的代码。如果有人能够通过代码并给我一行一行的傻瓜式解释,那么也许我终于明白了。



在此先感谢为您提供帮助!



ex。创建下面的金字塔:

$ block
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7




  class Pyramid {

public static void main(String [] args){

int x = 7; (int i = 1; i
(int j = 1; j< = x-i; j ++)
System.out.print(); (int k = i; k> = 1; k--)
System.out.print((k> = 10)?+ k:+ k ); (int k = 2; k< = i; k ++)
System.out.print((k> = 10)?+ k:+ k);


System.out.println();




$ div class =h2_lin>解决方案

在金字塔中有7行,所以第一个for循环遍历行,
第二个for循环打印了一堆空格,以便三角形不会显示为:

  1 
2 1 2
3 2 1 2 3




第三个for循环(with k),有一个条件运算符,像这样工作: > 布尔表达式? result-if-true:result-if-false

所以要么把数字k加到字符串,或者增加一个空格,然后把数字k加到字符串中。



第四个循环做类似的事情。


I am in a beginner java programming class and currently reviewing loops. If there is one thing I just do not understand, it's pyramids. I have researched the book exercises online and found the solutions to the pyramid examples, but even seeing the code, I still don't understand and couldn't recreate the answers if my life depended on it.

Below is a pyramid example and the code that creates it. If someone could walk through the code and give me a line by line 'for dummies' explanation of what is going on then maybe I'll finally understand.

Thanks in advance for you help!

ex. create the following pyramid:

class Pyramid {

    public static void main(String[] args) {

        int x = 7;

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

            for (int j = 1; j <= x - i; j++)
                System.out.print("   ");

            for (int k = i; k >= 1; k--)
                System.out.print((k >= 10) ?+ k : "  " + k);

            for (int k = 2; k <=i; k++)
                System.out.print((k >= 10) ?+ k : "  " + k);
            System.out.println();
        }
    }
}
解决方案

There are 7 rows in the pyramid, so the first for loop is looping over the rows,the second for loop is printing a bunch of spaces so that the triangle doesnt appear as:

1
2 1 2
3 2 1 2 3

The third for loop (with k), has a conditional operator which works like this:

boolean-expression ? result-if-true : result-if-false

So it either adds the number k to the string, or adds a space and then the number k to the string.

Fourth loop does a similar thing.

这篇关于解释在Java中创建一个金字塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:41