Java在if结尾处继续

Joh*_*ost 9 java if-statement continue

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

例:

int a = 5;
if(a == 5)
{
// some code
continue;
}
Run Code Online (Sandbox Code Playgroud)

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

Ósc*_*pez 21

也许那段代码在loop(for/while/do...while)中?否则放入条件语句是没有任何意义的continue.

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

  • 你是对的,我完全错过了围绕它的 for 循环。谢谢! (3认同)

cor*_*iKa 5

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);
}
Run Code Online (Sandbox Code Playgroud)