I want to break a while loop of the format below which has an if statement. If that if statement is true, the while loop also must break. Any help would be appreciated.
while(something.hasnext()) {
do something...
if(contains something to process){
do something
break if condition and while loop
}
}
You can't break out of if statement until the if is inside a loop. The behaviour of the break statement is well specified and, generally, well understood. An inexperienced coder may cause crashes though a lack of understanding in many ways. Misuse of the break statement isn't special.
Exit an if Statement With break in Python The break is a jump statement that can break out of a loop if a specific condition is satisfied. We can use the break statement inside an if statement in a loop. The main purpose of the break statement is to move the control flow of our program outside the current loop.
In the code above, you see a break in an if body. break can only exit out of an enclosing loop or an enclosing switch statement (same idea as an enclosing loop, but it's a switch statement). If a break statement appears in an if body, just ignore the if.
The break
keyword does exactly that. Here is a contrived example:
public static void main(String[] args) {
int i = 0;
while (i++ < 10) {
if (i == 5) break;
}
System.out.println(i); //prints 5
}
If you were actually using nested loops, you would be able to use labels.
An "if" is not a loop. 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.
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