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

标签 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 
<小时/>
 * * * * * * * * * 
* * * * * * * * * * 

第九行和第十行不正确

最佳答案

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

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

关于java - Java中使用for循环的等边三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204036/

相关文章:

java - 识别多线程 MQTT 发布者中的瓶颈

ruby - 从 Ruby 控制台测试 Ruby on Rails OAuth API

Linux - 如何从数组中找到短语

objective-c - 如何轻松重定向 NSTextView 中的控制台输出?

c++ - 涉及文件末尾时保持控制台屏幕

java - 如何在旧版 Java 应用程序上使用 com.opensymphony.oscache 查找内存泄漏

java - 如何包装 Google Guice 的 Injector 方法?

java - 无法让 javac 自动重新编译源文件

java - 更新文件时在 Dropbox API 中保留区分大小写的文件名

python - 如何向终端应用程序编写透明包装器?