简体   繁体   中英

Pyramid of asterisk using while loop in java

Is there possibilities that while loop can make a pyramid of asterisk in java?

    int num,num_ast;
    String asterisk= "*";

    Scanner pal = new Scanner (System.in);

    System.out.print("Enter number of asterisk: ");
    num_ast = pal.nextInt();

    num=0;
    while(num < num_ast)
    {
        System.out.println(asterisk);
        asterisk += "*";
        num++;
    }

this line only creates a right triangle of asterisk. Thanks.

Think of your pyramid as drawn on a coordinate system. You need to make sure that both the x-coordinate and the y-coordinate move in the whole program.

Scanner pal = new Scanner (System.in);
System.out.println("Enter the number of rows you want");
int n = pal.nextInt();
int rows = 0;
while (rows < n)
{
    int column = 0;
    while (column < n - rows)
    {
        System.out.print(" ");
        column++;
    }
    int currentStars = 0;
    while (currentStars <= rows)
    {
        System.out.print(" *"); 
        currentStars++;
    }
    System.out.print("\n");
    rows++;
}

This should get your program running. However, take time to understand why this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM