如果我们在for循环中有一个if语句,它会停止循环或if条件......
例:
for (int i = 0; i < array.length; i++) {
if (condition) {
statement;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 10
您也可以打破'if'语句,如果您愿意,在这种情况下可能有意义:
for(int i = 0; i<array.length; i++)
{
CHECK:
if(condition)
{
statement;
if (another_condition) break CHECK;
another_statement;
if (yet_another_condition) break CHECK;
another_statement;
}
}
Run Code Online (Sandbox Code Playgroud)
你也可以打破标签{}声明:
for(int i = 0; i<array.length; i++)
{
CHECK:
{
statement;
if (another_condition) break CHECK;
another_statement;
if (yet_another_condition) break CHECK;
another_statement;
}
}
Run Code Online (Sandbox Code Playgroud)
选择的答案几乎是正确的.if break
语句被混合label
然后它可以在 if
语句中使用而不需要在循环中.以下代码完全有效,编译和运行.
public class Test {
public static void main(String[] args) {
int i=0;
label:if(i>2){
break label;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我们删除标签,则无法编译.