最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Comparing three integer values - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Oct 18, 2011 at 20:36 Michael Berkowski 271k47 gold badges450 silver badges393 bronze badges asked Oct 18, 2011 at 20:35 user979431user979431 3572 gold badges3 silver badges10 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 10

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.

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;
    }

In JavaScript, your safest bet is a === b && b === c. I always avoid using == in favor of === for my own sanity. Here's a more detailed explanation.

In Scala you can use tuples for this:

(a, b) == (c, c)

This will check a == c and b == c, i.e same as a == b == c

To get the max value out of three numbers, one line method:

int max = (a > b && a > c) ? a : ((b > a && b > c) ? b : c);

发布评论

评论列表(0)

  1. 暂无评论