在Java中使用while循环的星号金字塔

时间:2018-09-23 06:10:57

标签: java

在Java中,while循环是否有可能使星号金字塔化?

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

此行仅创建星号的直角三角形。谢谢。

1 个答案:

答案 0 :(得分:-1)

考虑一下在坐标系上绘制的金字塔。您需要确保x坐标和y坐标都在整个程序中移动。

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

这应该使您的程序运行。但是,请花一些时间来了解其工作原理。