Is there any cleaner way to write multiple if-statements in Java

Ale*_*ang 2 java if-statement

I have an if-else structure in Java as follow:

                    if (A || B || C){
                        if (A){
                            //Do something
                        }
                        if (B){
                            //Do something
                        }
                        if (C){
                            //Do something
                        }
                    } else {
                        //Do something
                    }
Run Code Online (Sandbox Code Playgroud)

I want to know if there is any cleaner and easier way to replace this?

Era*_*ran 5

If A,B and C are conditions which are expensive to evaluate, you could use an additional flag to make sure they are only evaluated once:

boolean found = false;
if (A) {
    //Do something
    found = true;
}
if (B){
    //Do something
    found = true;
}
if (C){
    //Do something
    found = true;
}
if (!found) {
    //Do something
}
Run Code Online (Sandbox Code Playgroud)

Otherwise (i.e. if they are not expensive to evaluate), I'd keep your current conditions.

  • 谢谢,我认为这可以减少时间复杂度,因为在我的情况下,A,B,C是一些复杂的条件 (3认同)