嵌套for循环

时间:2014-03-24 05:49:49

标签: java for-loop nested-loops

关于这段代码,有一件事让我烦恼

    for (int i = 0; i<10; i++)
    {
          for (int c = 0; c < 10; c++)                  
              if(i == c)
                  System.out.print("*");
              else
                  System.out.print("-");

        System.out.println(".");
    }

我知道内部for循环必须在外循环再次循环之前完成。为什么System.out.println(“。”)只在内部循环中出现一次,即使它应该循环多次?

8 个答案:

答案 0 :(得分:2)

因为它位于内部for循环的一侧,所以在循环体周围使用括号以获得更好的可读性并避免这种混淆

答案 1 :(得分:2)

该行

System.out.println(".");

在嵌套for之外。如果你想要它,你应该使用括号{}

for (int i = 0; i < 10; i++) {
    for (int c = 0; c < 10; c++) {
        if (i == c) {
            System.out.print("*");
        } else {
            System.out.print("-");
        }
        System.out.println(".");
    }
}

请记住,如果不放置括号{}for循环的主体将只是一个语句(for声明旁边的语句)。< / p>

答案 2 :(得分:1)

不确定您的期望,但您的代码相当于:

for (int i = 0; i<10; i++)
{
      for (int c = 0; c < 10; c++) {
          if(i == c) {
              System.out.print("*");
          } else {
              System.out.print("-");
          }
      }

      System.out.println("."); // This is OUTSIDE the inner loop.
}

故事的道德:如有疑问,请使用括号。

答案 3 :(得分:1)

您的最终陈述是外部循环的一部分。

  

的System.out.println( “”);

由于内部循环中只有一个if-else语句,因此不需要大括号。 始终使用大括号来定义循环的范围并为了便于阅读。

for (int i = 0; i<10; i++)
{
      for (int c = 0; c < 10; c++) {                 
          if(i == c) {
              System.out.print("*");
          } 
          else {
              System.out.print("-");
          } 
      }

    System.out.println(".");
}

答案 4 :(得分:1)

内循环必须完成所有的传递/次数,而不是仅在再次运行父循环之前完成一次。

答案 5 :(得分:1)

for (int i = 0; i<10; i++)
{
      for (int c = 0; c < 10; c++)  
          {            
          if(i == c)
              System.out.print("*");
          else
              System.out.print("-");
          }
    System.out.println(".");//The . would get printed 10 times as it is inside first for loop.
}

答案 6 :(得分:1)

这种混乱是因为没有 Curly Braces 。你的代码没有任何错误。令你困惑的最后一个System.out.println(".");是外循环的一部分。所以你的代码等同于:

for (int i = 0; i<10; i++)
{
      for (int c = 0; c < 10; c++) {                 
          if(i == c){
              System.out.print("*");
          }
           else{
              System.out.print("-");
          }
    System.out.println(".");
    }
}

答案 7 :(得分:0)

代码中的Sysout属于外部循环,而不属于内部循环。

如果你没有在你的for循环之后放置大括号,那么它只需要一个语句。

这适用于你的情况。

for (int i = 0; i<10; i++)
{
      for (int c = 0; c < 10; c++)                  
       {   if(i == c)
              System.out.print("*");
          else
              System.out.print("-");

    System.out.println(".");}
     }
 }
相关问题