【问题标题】:In Java, how would I code a pyramid of asterisks by using nested for loops?在 Java 中,我将如何使用嵌套的 for 循环来编写星号金字塔?
【发布时间】:2020-05-29 21:49:29
【问题描述】:

我正在处理一项任务,我必须使用嵌套循环来编写位于其一侧的星号金字塔。 该程序的输出应如下所示:

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

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

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

    }
}

这是我的输出:

****
***
**
*

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

任何帮助将不胜感激。

【问题讨论】:

  • 一种方法是计算每行上的星号是否正确。然后在每行打印出您认为在打印之前需要打印的星号数量。我认为这些计算是错误的。
  • for(int c = a; c &lt; 4; c++):想想当你开始这个循环时a有什么价值。

标签: java loops nested-loops


【解决方案1】:

你的逻辑有几个错误:

  1. 由于您只需要 7 个 rows,因此第一个循环应该迭代到 a &lt; 7
  2. 在前 3 行中,您的 nested loop 应该从 0 迭代到 a
  3. 之后,另一个nested loop 应该从a 变为7
  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();
}

输出:

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

编辑:

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

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

【讨论】:

  • 您实际上并不需要内部条件:将外部循环分成两个循环,从 [0..4) 到 [4..7)。
  • 是的,但我记得分配了这样的练习来教授nested loops的概念
  • 你仍然有嵌套循环。
  • 哦,我明白了。我理解我在逻辑中犯的错误。我现在还看到内部 for 循环应该进入 if 语句内部——而不是相反。谢谢!
  • @AndyTurner 感谢您的建议!我编辑了答案以包含它。
【解决方案2】:

你已经接近了。试试这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多