Search code examples
javaloopscoding-styleconditional-statementslogical-operators

How to break out of multiple if blocks inside while loop in java?


I wanted to break out of each if condition and make a validation for i, Currently, what is happing is after all the if condition is verified only the only loop is getting considered, is there any logic to make the code validate after each if condition, The simple soltion is to add the (i<=10) in each of the if condition. is there any other alternative?

code sample below
    while(i<=10){
      if(condition1){
          //action1
        }
      if(condition2){
          //action2
        }
      if(condition3){
          //action3
        }
      if(condition4){
          //action4
        }
      }

Solution

  • <outerloop_name>:
    while(i<=10){
          if(condition1){
              //action1
              break <outerloop_name>;
            }
          if(condition2){
              //action2
              break <outerloop_name>;
            }
          if(condition3){
              //action3
              break <outerloop_name>;
            }
          if(condition4){
              //action4
              break <outerloop_name>;
            }
          }