首页 > 解决方案 > 我怎样才能在java中修复这个星星金字塔

问题描述

我必须通过用户输入打印星星的金字塔,用户输入:多少行,多少列。我盯着一颗星,每次迭代将星数增加 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

解决方案


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

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

推荐阅读