Java 有没有办法在原始条件变为假之前跳出 while 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2649473/
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
Is there a way to break out of a while loop before the original condition is made false?
提问by David
Is there a way to break out of a while loop before the original condition is made false?
有没有办法在原始条件变为假之前跳出 while 循环?
for example if i have:
例如,如果我有:
while (a==true)
{
doSomething() ;
if (d==false) get out of loop ;
doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true() ;
}
Is there any way of doing this?
有没有办法做到这一点?
采纳答案by BalusC
Use the break
statement.
使用break
语句。
if (!d) break;
Note that you don't need to compare with true
or false
in a boolean expression.
请注意,您不需要与true
或false
在布尔表达式中进行比较。
回答by Carl Manaster
break
is the command you're looking for.
break
是您要查找的命令。
And don't compare to boolean constants - it really just obscures your meaning. Here's an alternate version:
并且不要与布尔常量进行比较-它实际上只是掩盖了您的含义。这是一个替代版本:
while (a)
{
doSomething();
if (!d)
break;
doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true();
}
回答by Jo?o Silva
Yes, use the break
statement.
是的,使用break
语句。
while (a==true)
{
doSomething() ;
if (d==false) break;
doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true() ;
}
回答by Matthew Jones
Try this:
尝试这个:
if(d==false) break;
This is called an "unlabeled" break statement, and its purpose is to terminate while
, for
, and do-while
loops.
这就是所谓的“无标签” break语句,其目的是终止while
,for
以及do-while
循环。
参考这里。
回答by mportiz08
while(a)
{
doSomething();
if(!d)
{
break;
}
}
回答by Chris
Do the following Note the inclusion of braces - its good programming practice
做以下注意大括号的包含 - 它的良好编程习惯
while (a==true)
{
doSomething() ;
if (d==false) { break ; }
else { /* Do something else */ }
}
回答by Carl
while ( doSomething() && doSomethingElse() );
change the return signature of your methods such that d==doSomething()
and a==doSomethingElse()
. They must already have side-effects if your loop ever escapes.
更改您的方法的返回签名,例如d==doSomething()
和a==doSomethingElse()
。如果您的循环逃脱,它们一定已经产生了副作用。
If you need an initial test of so value as to whether or not to start the loop, you can toss an if
on the front.
如果您需要对是否开始循环进行如此有价值的初始测试,您可以if
在前面扔一个。