简体   繁体   中英

How to Break an Else If Condition

I want to break out of an else if condition where it has an inner if condition, if the inner if condition inside becomes true like below, please suggest me a way.

 if(condition1=true){

        }
    else if(condition2=true){

           if(condition3=true){

              do activity 1;
              //I want to break here if condition3 is true, without executing activity 2 & 3
            }

          do activity 2;
          do activity 3;

    }
else if(condition2){
       if(condition3){
              do activity 1;
              //I want to break here if condition3 is true, without executing activity 2 & 3
        }
        else
        {
              do activity 2;
              do activity 3;
        }
}

In java you can use break only in loop for or while or switch/case or named blocks

But you if you have method void you can write return;

Something like:

void foo(){

if(condition1=true){

        }
    else if(condition2=true){

           if(condition3=true){

              do activity 1;

              return;
            }

          do activity 2;
          do activity 3;

    }
}

Others already answered with restructuring the blocks. If checking of conditions don't need to happen in sequence, you can do-

if(condition3=true){
    do activity 1;
} else if(condition2=true){
    do activity 2;
    do activity 3;
} else if(condition1=true){

}

Well, you could go for an else statement.

...
if(condition3=true){
    do activity 1;
} else {
    do activity 2;
    do activity 3;
}
...

Or, if you prefer, you can extract that entire block of code to a separate function and have it return right after activity 1.

I think you could also use a named block:

...
doActivities:{
    if(condition3=true){
        do activity 1;
        break doActivities;
    } else {
        do activity 2;
        do activity 3;
    }
}
...

However, that's dangerously close to an outright goto and is probably not recommended.

No need for break. This should do it.

if(condition1=true){

} else if(condition2=true){
    if(condition3=true){
        do activity 1;
        //I want to break here if condition3 is true, without executing activity 2 & 3
    } else {
        do activity 2;
        do activity 3;
    }
}

In fact, I would try the way that is easier to read:

if(condition1)
{

}
else if(condition2 && condition3) {
      do activity 1;

}
else if(condition2 && !condition3) {
      do activity 2;
      do activity 3;
}

This way you avoid nested ifs and keep your code very easy to read.

If-else patterns like this strongly hint at having some class structure to handle the cases.

Activity activity = ActivityFactory.getActivity(conditionCause);
activity.execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM