Evan Ross Davis
Evan Ross Davis

Reputation: 1

Is this a valid way to test for equality among 3 values?

public static double tripleBet(Dice dice, double betAmount) {
    double payout = 0.0;
    double three_rolled = 3;

    if (dice.getFirst() == dice.getSecond() && dice.getThird() == dice.getFirst()) {
        payout = betAmount * three_rolled;
    } else {
        payout = -betAmount;
    }
    return payout;

}

Here I am comparing die in a game called "Chuck-a-luck." I need to simply return a payout amount if the player has bet the dice will all be the same.

The expression in the conditional statement is my main concern. I'd like to know if it is valid or "good practice" to write like this.

Any other advice is welcomed as well.

Upvotes: 0

Views: 88

Answers (3)

404 Brain Not Found
404 Brain Not Found

Reputation: 605

So far, I don't see any problems with the code you have given.

Here are some cosmetic updates you can make to your code. Will make it look much simpler and reduce the number of lines and save you some memory as well in the process.

public static double tripleBet(Dice dice, double betAmount) {

    double three_rolled = 3;

    // Using Ternary Operator we eliminated the need for a separate variable "payout" by simple returning the resultant values to the caller method.

    return (dice.getFirst() == dice.getSecond() && dice.getThird() == dice.getFirst()) ? betAmount * three_rolled : -betAmount;
}

P.S : If the value of the variable three_rolled will always stay as 3 then i think you can either assign it to a byte or a similar data type. Don't need a double for a value this small. Better memory management leads to a happy compiler and cleaner codes.

Upvotes: 0

Jai
Jai

Reputation: 8363

What you are doing is fine. It is also possible to write your own helper method for this.

@SafeVarargs
public static final boolean equals(Object... objs) {
    if (objs== null || objs.length < 2) return false; // You may return true or throw exception

    for (int i = 0; i < nums.length - 1; i++) {
        if (!Objects.equals(objs[i], objs[i + 1])) return false;
    }

    return true;
}

This will make it easier for you to read later on, provided you may have to a use-case where you compare even more values.

 if (Helper.equals(dice.getFirst(), dice.getSecond(), dice.getThird()) {}

Upvotes: 1

user207421
user207421

Reputation: 310980

Yes, it is valid. The == operator is transitive, meaning that A == B and B == C implies that A == C.

I would therefore probably write it as

if (dice.getFirst() == dice.getSecond() && dice.getSecond() == dice.getThird())

Upvotes: 2

Related Questions