首页 > 解决方案 > 在Java中打印*的金字塔

问题描述

我想知道你能不能帮帮我。我正在尝试在 java 中编写一个嵌套的 for 循环,它显示一个数字金字塔三角形,看起来像

___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#

这是我到目前为止所拥有的:

class Triagle {
    public static void printTriagle(int n) {
        for (int i = 0; i < n; i++) {
            for (int j = n - i; j > 1; j--) {
                System.out.print(" ");
            }

            for (int j = 0; j <= i; j++) {
                // printing stars
                System.out.print("* ");
            }

            System.out.println();
        }
    }

    public static void main(String[] args) {
        printTriagle(12);//I want to set the triangle to be height of 12
    }
 }

我的结果不等于预期的输出:

___________*#
__________*_*#
_________*_*_*#
________*_*_*_*#
_______*_*_*_*_*#
______*_*_*_*_*_*#
_____*_*_*_*_*_*_*#
____*_*_*_*_*_*_*_*#
___*_*_*_*_*_*_*_*_*#
__*_*_*_*_*_*_*_*_*_*#
_*_*_*_*_*_*_*_*_*_*_*#
*_*_*_*_*_*_*_*_*_*_*_*#

标签: java

解决方案


我已经更新了您的代码并添加了注释,以便您理解。参考下面的代码:

public static void printTriagle(int n) {
    for (int i = 0; i < n; i++) {

        for (int j = n - i; j > 1; j--) {
            System.out.print("_");
        }
        String s = "_";
        if (i + 1 >= n) // check if it is the last line
            s = "*"; // change to print * instead of _

        for (int j = 0; j <= i; j++) {
            // printing stars
            if (j == i)
                System.out.print("*#"); // check if the last print of the line
            else if (j == 0)
                System.out.print("*" + s); // check if the first print of the line
            else
                System.out.print(s + s);
        }

        System.out.println();
    }
}

结果:

___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#

推荐阅读