【问题标题】:Nested For Loop - Why with the code written like this, do I get more asterix than println?嵌套 For 循环 - 为什么使用这样编写的代码,我得到的 asterix 比 println 多?
【发布时间】:2014-07-14 23:56:36
【问题描述】:
int n = 10;

for(int i = 0; i < n; i++)
  {
      for(int j = 0; j <= i; j++)
      System.out.print("*");
      System.out.println();
  }

问题说真的,在这个任务上有点挣扎,我尝试了这种方式并且它有效,但我不太明白为什么,这样写,看起来会有相同数量的 println 语句作为星号 (*) 符号。这显然不会形成所需的三角形(它只会形成一条与 n 一样长的线)。所以我能明白为什么这有效的唯一方法是使用 println 语句为初始 for 循环绘制另一个大括号。我想这是我忘记了 for 循环如何执行其代码的事情。但是有人可以帮我解释一下吗?

那么这样写代码不是更好吗?

for(int i = 0; i < n; i++) {
   for (int j = 0; j <= i; j++) {            
          System.out.print("*");
        }
        System.out.println();
   }

【问题讨论】:

    标签: java for-loop nested-loops


    【解决方案1】:

    因为内循环的主体只是一个语句

    for(int j = 0; j <= i; j++)
          System.out.print("*");
    

    没有括号

    改成

     for(int j = 0; j <= i; j++) { 
          System.out.print("*");
          System.out.println();
     }
    

    或者你甚至不需要这样的第二条语句

     for(int j = 0; j <= i; j++) { 
          System.out.println("*");
     }
    

    【讨论】:

    • 你是对的!该死的,应该从while循环的工作中记住这一点!非常感谢您的帮助先生!
    • yes 可读 + 如果你想在内循环打印所有 * 后打印新行
    猜你喜欢
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2019-05-13
    • 2021-08-13
    • 2014-11-05
    相关资源
    最近更新 更多