Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing three integer values

Is something like this ever possible?

if(a == b == c)

or is

if((a== b) && (b == c)) 

is the only way?

or what is the coolest way to do that?

like image 670
user979431 Avatar asked Oct 18 '11 20:10

user979431


2 Answers

In some languages you can use that shorthand. For example in Python a == b == c is roughly equivalent to the expression a == b and b == c, except that b is only evaluated once.

However in Java and Javascript you can't use the short version - you have to write it as in the second example. The first example would be approximately equivalent to the following:

boolean temp = (a == b);
if (temp == c) {
    // ...
}

This is not what you want. In Java a == b == c won't even compile unless c is a boolean.

like image 83
Mark Byers Avatar answered Oct 24 '22 12:10

Mark Byers


In java - we don't have the == shortcut operator. so we end up doing individual equalities.

But If you think you will need functionality a lot with varying number of arguments, I would consider implementing a function like this. The following is the sample code without handling exceptional conditions.

 public static boolean areTheyEqual(int... a) {
        int VALUE = a[0];   
        for(int i: a) {
            if(i!= VALUE)
                return false;
        }       
        return true;
    }
like image 36
java_mouse Avatar answered Oct 24 '22 11:10

java_mouse