6

Is there an operator in Java that will give a result of false if either conditions are false, but if both are true or both false the result will be true?

I have some code that relies on a user entering some values for a process to run. As the user should only be able to enter x or y but not both or none I would like to show an error message in this case.

1 Answer 1

24

You want XNOR, basically:

if (!(a ^ b)) 

or (more simply)

if (a == b) 

where a and b are the conditions.

Sample code:

public class Test { public static void main(String[] args) { xnor(false, false); xnor(false, true); xnor(true, false); xnor(true, true); } private static void xnor(boolean a, boolean b) { System.out.printf("xnor(%b, %b) = %b\n", a, b, a == b); } } 

Produces this truth table;

xnor(false, false) = true xnor(false, true) = false xnor(true, false) = false xnor(true, true) = true 
Sign up to request clarification or add additional context in comments.

12 Comments

Jon, it would probably be beneficial to show the full logic table for the XOR operator in this case. I would do it here, but the comment formatting is horrible for this.
Thanks, that was what I was looking for! I knew there was an operator, just couldn't remember it :)
@James: I've edited this with a simpler way of doing this - the equality operator!
Also, yes, != is simpler. But !XOR is the correct boolean operator for this case. So I still like your answer the best.
This question was given in the context of Java. In Java, the ^ symbol represents the bit-operation XOR.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.