Is there a way to break out of a while loop before the original condition is made false?
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?
Breaking Out of While Loops. To break out of a while loop, you can use the endloop, continue, resume, or return statement.
break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs.
Just use the break inside the "if" and it will break out of the "while". If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.
Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.
Use the break
statement.
if (!d) break;
Note that you don't need to compare with true
or false
in a boolean expression.
break
is the command you're looking for.
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();
}
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.
Reference here.
break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With