Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java operator to check if either conditions are false, but not both or none

Tags:

java

logic

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.

like image 226
James Goodwin Avatar asked Jan 11 '10 15:01

James Goodwin


1 Answers

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
like image 186
Jon Skeet Avatar answered Sep 28 '22 02:09

Jon Skeet