Java中使用for循环的等边三角形

时间:2015-05-13 01:18:44

标签: java console

我正在尝试绘制星号字符的等边三角形,但当用户输入行号时,行将被绘制为"x",整个三角形将为"*"但我在空格中有错误。

这是我的代码:

int number_of_stars = getHeight();
for (int rows=1; rows <= getHeight(); rows++) 
       {
        for (int spaces=1; spaces <= number_of_stars; spaces++) 
        {
            System.out.print(" ");
        }

        if(rows == getRowNum()){
            for (int star=1; star <= rows; star++) 
            {
                System.out.print("x");
                System.out.print(" ");
                }
            System.out.println("");
            rows = getRowNum()+1;
            System.out.print(" ");
            System.out.print(" ");
            System.out.print(" ");

        }
        for (int star=1; star <= rows; star++) 
        {
            System.out.print("*");
            System.out.print(" ");
            }
        System.out.println("");
        number_of_stars = number_of_stars - 1;
        }

,输出

      * 
     * * 
    * * * 
   * * * * 
  * * * * * 
 * * * * * * 
x x x x x x x 
 * * * * * * * * * 
* * * * * * * * * * 

第九行和第十行不正确

2 个答案:

答案 0 :(得分:0)

我相信你想要一个简单的if-else,当你添加一个额外的循环来打印x时,它会推动你的对齐。我想你只是想要,

public static void main(String[] args) {
    int number_of_stars = getHeight();
    for (int rows = 1; rows <= getHeight(); rows++) {
        for (int spaces = 1; spaces <= number_of_stars; spaces++) {
            System.out.print(" "); // <-- indent(s)
        }
        for (int star = 1; star <= rows; star++) {
            if (rows == getRowNum()) {
                System.out.print("x"); // <-- one row is "x"
            } else {
                System.out.print("*"); // <-- others are "*"
            }
            System.out.print(" ");
        }
        System.out.println("");
        number_of_stars = number_of_stars - 1;
    }
}

答案 1 :(得分:0)

IMO仅对特定行号所需的更改是打印*而不是public static void main(String[] args) { int userRowNumber = 5; int height = 10; int number_of_stars = height; String charToPrint; for (int rows=1; rows <= height; rows++) { charToPrint = "*"; if(rows == userRowNumber){ charToPrint = "x"; } for (int spaces=1; spaces <= number_of_stars; spaces++) { System.out.print(" "); } for (int star=1; star <= rows; star++) { System.out.print(charToPrint); System.out.print(" "); } System.out.println(""); number_of_stars = number_of_stars - 1; } } ,为此您只需更改要打印的字符即可。我试过这个示例代码:

append

打印预期的内容。对于代码中的问题,我建议您自己调试并找到它。