命令.. 打破; 在 Java 中怎么办。?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4154553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The Command.. break; in Java what if.?
提问by WM.
What if we have an if statement inside a for loop, would it stop the loop or the if condition...
如果我们在 for 循环中有一个 if 语句,它会停止循环还是 if 条件...
Example:
例子:
for (int i = 0; i < array.length; i++) {
if (condition) {
statement;
break;
}
}
采纳答案by brain
The break
statement has no effect on if statements. It only works on switch
, for
, while
and do
loops. So in your example the break would terminate the for
loop.
该break
语句对 if 语句没有影响。它仅适用于switch
,for
,while
和do
循环。因此,在您的示例中,中断将终止for
循环。
See this sectionand this sectionof the Java tutorial.
回答by Cameron Skinner
It will stop the loop.
它将停止循环。
回答by Nico Huysamen
The break command inside the IF statement will exit the FOR loop.
IF 语句中的 break 命令将退出 FOR 循环。
回答by Buhake Sindi
Once the condition is met and the statement has successfully been executed (let's assuming no exception is thrown), then the break
exits from the loop.
一旦满足条件并且语句已成功执行(假设没有抛出异常),则break
退出循环。
回答by Jeen Broekstra
a break
statement (and its companion, 'continue', as well) works on a surrounding loop. An if
-statement is not a loop. So to answer your question: the break
in your code example will jump out of the for
-loop.
一个break
语句(以及它的伴随,'continue',以及)适用于周围的循环。-if
语句不是循环。所以回答你的问题:break
你的代码示例中的 将跳出for
-loop。
回答by semicontinuity
You can break out of just 'if' statement also, if you wish, it may make sense in such a scenario:
如果您愿意,您也可以脱离“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;
}
}
you can also break out of labeled {} statement:
您还可以跳出带标签的 {} 语句:
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;
}
}
回答by Reza
The selected answer is almostright. if break
statement be mixed by label
then it can be used in if
statement without needing to be in a loop. The following code is completely valid, compiles and runs.
所选答案几乎是正确的。ifbreak
语句被混合到label
then 它可以在 if
语句中使用而无需在循环中。以下代码完全有效,编译运行。
public class Test {
public static void main(String[] args) {
int i=0;
label:if(i>2){
break label;
}
}
}
However if we remove the label, it fails to compile.
但是,如果我们删除标签,它将无法编译。
回答by PedroZGZ
for (int i = 0; i < array.length; i++) {
jumpIf: if (condition) {
statement;
break jumpIf;
}
}