在 Java 中,我将如何使用嵌套 for 循环编写星号金字塔代码?

In Java, how would I code a pyramid of asterisks by using nested for loops?

我正在做一项作业,我必须使用嵌套循环来对一侧的星号金字塔进行编程。 该程序的输出应如下所示:

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

当我运行我的程序时,它只显示代码的最后四行。我不知道为什么前三个没有出现。 这是我的代码:

public class Main
{
    public static void main(String[] args) {

        for(int a = 0; a < 8; a++) //1
        {
            if(a < 4){
                for(int b = a; b < 4; b++)
                {
                    System.out.print("*");
                }

            }
            if(a >= 4)
                for(int c = a; c < 4; c++)
                {  
                    System.out.print("*");
                }

            System.out.println();
        } //loop 1

    }
}

这是我的输出:

****
***
**
*

(输出后有一些我没有包含的空 space。这是由外部 for 循环迭代八次造成的。)我如何让我的程序正确显示所有代码,而不仅仅是最后四行?

如有任何帮助,我们将不胜感激。

你的逻辑有几个错误:

  1. 因为你只需要 7 rows,第一个循环应该迭代到 a < 7
  2. 在前 3 行中,您的 nested loop 应该从 0 迭代到 a
  3. 在那之后,另一个 nested loop 应该从 a7
  4. 最好使用 if-else 而不是两个 if 语句

这是我测试过的完整解决方案:

for(int a = 0; a < 7; a++) {
     if(a < 4){
          for(int b = 0; b <= a; b++)
               System.out.print("*");
     }else {
          for(int c = a; c < 7; c++)
               System.out.print("*");
     }
     System.out.println();
}

输出:

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

编辑:

如评论中所述,您还可以将外循环拆分为两部分,以便删除条件,如下所示:

for(int a = 0; a < 4; a++) {
     for(int b = 0; b <= a; b++)
          System.out.print("*");
     System.out.println();
}
for(int a = 4; a <= 7; a++) {
     for(int b = a; b < 7; b++)
          System.out.print("*");
     System.out.println();
}

你很接近。尝试这样的事情:

int size = 4;

for(int line = 1; line < size * 2; line++) {
  if(line <= size) {
    for(int i = 0; i < line; i++) {
      System.out.print("*");
    }
  }
  else {
    for(int i = 0; i < size * 2 - line; i++) {
      System.out.print("*");
    }
  }
  System.out.println();
}