James Goodwin
James Goodwin

Reputation: 7406

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

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.

Upvotes: 6

Views: 10533

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500135

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

Upvotes: 24

Related Questions