Print pyramid of * in Java

Lemma :

I'm wondering if you could help me out. I'm trying to write a nested for loop in java that displays a number pyramid triangle that looks like

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

This is what I have so far:

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
    }
 }

My result is not equal to the expected output:

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

I have updated your code and added comments so that you can understand. Refer to the code below:

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();
    }
}

Result:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76061&siteId=1