10

我有一些书中的示例代码,作者总是在 if 的末尾使用 continue 。

例子:

int a = 5;
if(a == 5)
{
// some code
continue;
}

现在对我来说这没有任何意义。背后可能有某种质量管理推理,还是我只是错过了一些更大的观点?

4

4 回答 4

25

也许那段代码在循环(for/while/do...while)内?否则,将 a放在条件语句中没有任何意义。continue

事实上,孤立的 continue(例如:未嵌套在循环语句中的某个位置)将continue cannot be used outside of a loop在编译时产生错误。

于 2012-11-09T16:05:51.337 回答
5

继续用于进入循环的下一次迭代。所以这样的事情是有道理的。现在您可以使用任何条件(您的条件是a==5中断),以及您想要的任何业务逻辑(我的是一个愚蠢的、人为的例子)。

StringBuilder sb = new StringBuilder();
for(String str : strings) {
    sb.append(str);
    if(str.length() == 0) continue; // next loop if empty

    str = str.substring(1);
    sb.append(str);
    if(str.length() == 0) continue; // next loop if empty

    str = str.substring(1);
    sb.append(str);
    if(str.length() == 0) continue; // next loop if empty

    sb.append(str);
}
于 2012-11-09T16:06:18.740 回答
2

有时强制循环的早期迭代很有用。也就是说,您可能希望继续运行循环,但停止处理此特定迭代的主体中的其余代码。实际上,这是一个 goto 刚经过循环体,到循环结束的方式。continue 语句执行这样的操作。在 while 和 do-while 循环中, continue 语句导致控制直接转移到控制循环的条件表达式。在 for 循环中,控制首先进入 for 语句的迭代部分,然后进入条件表达式。对于所有三个循环,任何中间代码都被绕过。下面是一个示例程序,它使用 continue 导致每行打印两个数字: // Demonstrate continue.

class Continue
{ 
public static void main(String args[]) 
    { 
    for(int i=0; i<10; i++) 
        { 
    System.out.print(i + " "); 
    if (i%2 == 0)
    continue; 
    System.out.println(""); 
        } 
    } 
}

此代码使用 % 运算符检查 i 是否为偶数。如果是,则循环继续而不打印换行符。这是该程序的输出:

0 1
2 3
4 5
6 7
8 9

于 2012-11-09T16:12:43.677 回答
1

通常, continue 用于逃避深度嵌套的循环,或者只是为了清楚起见(有争议)。

有时 continue 也用作占位符,以使空循环体更清晰

for (count = 0; foo.moreData(); count++)
  continue;

这是我个人不使用继续的口味问题。

于 2012-11-09T16:11:06.193 回答