Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an 'else' based on the result of two (or more) previous 'if's?

Tags:

java

Currently I have some code in the if (roobaf) block which depends on foo and bar being false. I can check these conditions again within the block but it feels like unnecessary repetition of code.

if (foo) {
    // some code
}

/*else*/ if (bar) {   // bar is a condition which needs to be checked 
                      // whether 'foo' is true or false
// more code
}

if (roobaf) { 

   if (!foo && !bar) {
      // even more code
    }

}

The problem is that if bar is just an if, then roobaf will be reached even if foo is true.

If I change bar to an else if then if foo is true then bar will not be checked.

How do I make sure that foo and bar are always checked but that roobaf will only be checked if both foo and bar are checked?

roobaf is a condition which is not mutually exclusive with foo and bar so putting it first will not work.

like image 689
Chris A Avatar asked Mar 03 '23 18:03

Chris A


1 Answers

you could do something like this:

if (foo || bar) {
    if (foo) {
        // do something
    }
    if (bar) {
        // do something
    }
}
else {
    if (roobaf) {
        // do something else
    }
}
like image 173
nLee Avatar answered May 08 '23 10:05

nLee