简体   繁体   中英

checking for both true or both false

if I have the following logic to check for both true or both false but ignore the others, I write:

if (a) {
  if (b) {
    // do something when both true
  }
} else if (!b) {
  // do something when both false
}

is that the simplest you can write in java?

of course I can write

if (a && b) {
    // do something when both true
} else if (!a && !b) {
  // do something when both false
}

but I am thinking if it is possible to achieve this using only one if condition and else without condition, eg

if (some condition) {
    // do something when both true
} else {  // <-- check! only else, no more condition
  // do something when both false
}

Impossible is of course an acceptable answer to this question (if accompanied with explanation)

Thank you

Apologies for my initial XOR answer - I had misread your question. The correct answer is,

It is impossible in Java.

The reason is one of Boolean logic. When you have two logicals, A and B, then there are four possible states:

A  B
0  0    << A and B are false
0  1
1  0
1  1    << A and B are true

When you have a condition that says "Both A and B are true", you have just the last state. Unfortunately, the "else" (all the others) contains three possible states. You cannot have something that is true for one state, false for another, and "something else" for the other two. That's not how Boolean algebra works.

The answer is no . You can't have an else clause that runs only under certain conditions without using an else if . An else clause without else if will run every time the condition in the if clause is false. If you want to add additional constraints (such as both a and b are false) you need to use an else if .

There is nothing wrong with using else if though, and it makes your intention fairly clear:

if (a && b) {

} else if (!a && !b) {

}

You have three states you wish to handle differently -- though one case is to "do nothing."

if ( a && b )
{
    // Do something when both are true.
}
else if ( ! a && ! b )
{
    // Do something if both are false.
}

This is the most economical way to do what you want to achieve -- two tests for three cases.

Alternatively, if you can return 0 or 1 from your "boolean values" or your expressions, you could do something like:

switch ( a + b )
{
    case 0:
        // Do something when both a and b are "false."
        break;

    case 1:
        // Do something -- or nothing -- when a or b are "false" and the other is "true."
        break;

    case 2:
        // Do something when both a and b are "true."
        break;
}

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