Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break a while loop from an if condition inside the while loop?

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
   }
}
like image 557
SuperCoder Avatar asked May 08 '14 19:05

SuperCoder


People also ask

Can you put a break inside an if statement?

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.

How do you break out of a if loop?

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.

Does Break get out of an IF and a for 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.


2 Answers

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.

like image 74
assylias Avatar answered Sep 30 '22 19:09

assylias


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.

like image 30
Ernest Friedman-Hill Avatar answered Sep 30 '22 19:09

Ernest Friedman-Hill