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

Equilateral triangle in Java using for loop

我正在尝试绘制一个由星号字符组成的等边三角形,但是当用户输入行号 时, 行将被绘制为 "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 

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

第九行和第十行不正确

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

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

IMO 对特定行号的唯一更改是打印 x 而不是 * 并且为此您可以简单地更改要打印的字符。我试过这个示例代码:

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

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