我怎样才能在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:

   *   *   *   *

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

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


慕少森
浏览 82回答 1
1回答

喵喵时光机

乍一看,您似乎没有考虑打印星星后出现的空间。尝试像这样修改代码:private static void printStars(int rows, int columns){&nbsp; &nbsp; int stars = 1;&nbsp; &nbsp; while (rows > 0) {&nbsp; &nbsp; &nbsp; &nbsp; int spaces = rows;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i <= columns; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int sp = spaces; sp >= 1; sp--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int st = stars; st >= 1; st--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int sp = spaces; sp >= 1; sp--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; stars += 2;&nbsp; &nbsp; &nbsp; &nbsp; rows--;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java