我有一本书中的示例代码,作者总是在if语句的末尾使用continue。
例如:
int a = 5;
if(a == 5)
{
// some code
continue;
}
对我来说,这毫无意义。这背后可能存在某种质量管理的推理,或者我只是错过了一些更大的观点吗?
我有一本书中的示例代码,作者总是在if语句的末尾使用continue。
例如:
int a = 5;
if(a == 5)
{
// some code
continue;
}
对我来说,这毫无意义。这背后可能存在某种质量管理的推理,或者我只是错过了一些更大的观点吗?
也许那段代码在循环体内 (for/while/do...while
)?否则,在条件语句中放置 continue
是毫无意义的。实际上,一个孤立的continue
(例如:不在某个循环语句内部) 会在编译时产生错误:continue cannot be used outside of a loop
。
Continue用于进入循环的下一个迭代。因此,以下内容是合理的。现在,您可以使用任何条件(您的条件是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);
}
continue
之后加上注释“如果为空则退出循环”最好不要,这样会产生歧义。;-) - assyliasclass 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("");
}
}
}
通常,continue 用于跳出深度嵌套的循环,或仅仅为了清晰明了(有争议)。
有时候,continue 还被用作占位符,以便使空的 循环体 更加清晰明了。
for (count = 0; foo.moreData(); count++)
continue;
这是一个品味问题,我个人不使用“continue”。
continue
,将最后的3改为2。 - jlordofor
循环语句中,@Jamie。这很重要。 - sbi