繁体   English   中英

这将继续导致嵌套的for循环做什么?

[英]What will this continue cause the nested for-loop to do?

我已经搜索了SO,可以找到针对相似主题的问题,但是对于此特定问题和语言却一无所获。 在阅读了一些问答之后,并没有找到答案,我搜索了 ,结果为零。

在大学测验中有人问我这个问题:

如果我有:

int n = 3;
   for (int i = 1; i <= n; i++)  {
      System.out.print(" x ");
        for (int j = 1; j <= n; j++)  {
         System.out.println(" x ");
           continue;
           //no content here
        }
     }

在continue语句之后没有任何内容; 使用continue如何影响此循环? 它会导致第二个循环中的中断吗?该循环是否会继续迭代?

没有标签的continue语句将从最里面的while或do或者loop循环中的条件重新执行,并从更新表达式的最里面的for loop重新执行 它通常用于尽早终止循环的处理,从而避免深层嵌套if语句。

因此,对于您的程序而言, continue进行按键并没有多大意义。 它被用作一种逃生的东西。 例如:

aLoopName: for (;;) {
  // ...
  while (someCondition)
  // ...
    if (otherCondition)
      continue aLoopName;

说,如果您修改程序,例如:

int n = 3;
   for (int i = 1; i <= n; i++)  {
      System.out.print(" x ");
        for (int j = 1; j <= n; j++)  {
         if(j%2!=0)
         {
          System.out.println(" x ");
          continue;
         }
         else
         break;
     }

对于j = 2,这将破坏内部的 for循环。 希望你能理解。 :)

您问题的答案:

使用continue如何影响此循环? 它会导致第二个循环中的中断吗?该循环是否会继续迭代?

是:

第二个循环不会中断,它将继续进行迭代。 break关键字用于中断循环。

编辑

假设您有for循环:

for(int i = 0; i < 5; i++){
   continue;
}

continue in for执行for循环( i++ )语句以继续进行下一个迭代。

在其他循环中, while{}do{}while(); 事情不会像这样,并可能导致无限循环。

如果在continue下有一个代码,它将是无效代码 (无法访问的代码)。

您编写它的方式没有效果,因为它已经是最后一行了。 如果没有continue;循环将continue;

这两个代码块具有相同的效果:

for(int i = 0; i < 10; i++) {
   // .. code ..
}

for(int i = 0; i < 10; i++) {
   // .. code ..
   continue;
}

但是,以下代码段具有无法访问的代码:

for(int i = 0; i < 10; i++) {
   // .. code ..
   continue;
   // .. unreachable code ..
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM