我怎样才能在java中修复这个星形金字塔

问题描述 投票:0回答:1

我必须通过用户输入打印星形的质子,用户输入:行数和列数。我盯着一颗星,每次迭代时将星星增加2,然后将行减少1.我无法确定我需要做多少空间。

我要做的是:例子:

printStars(4,2) rows = 4 , columns = 2.
output :

   *       *
  ***     ***
 *****   *****
******* *******

printStars(3,3) rows= 3 , columns =3.
output : 

  *     *     *
 ***   ***   ***
***** ***** *****

printStars(3,4) rows = 3 , columns =4.
output:
  *     *     *     *
 ***   ***   ***   ***
***** ***** ***** *****

代码:

private static void printStars(int rows, int columns ) {

        int stars = 1;

        while (rows > 0) {

            int spaces = rows;

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


                for (int sp = spaces; sp >=1; sp--) {
                    System.out.print(" ");
                }
                for (int st = stars; st >= 1; st--) {
                    System.out.print("*");
                }

            }
            System.out.println();
            stars += 2;
            rows--;

        }

    }

我得到了什么:


printStars(3,4)
output:
   *   *   *   *
  ***  ***  ***  ***
 ***** ***** ***** *****
java
1个回答
4
投票

乍一看,似乎你没有考虑打印星星后的空间。尝试修改这样的代码:

private static void printStars(int rows, int columns)
{

    int stars = 1;

    while (rows > 0) {

        int spaces = rows;

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

            for (int sp = spaces; sp >= 1; sp--) {
                System.out.print(" ");
            }
            for (int st = stars; st >= 1; st--) {
                System.out.print("*");
            }
            for (int sp = spaces; sp >= 1; sp--) {
                System.out.print(" ");
            }
        }
        System.out.println();
        stars += 2;
        rows--;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.