为了账号安全,请及时绑定邮箱和手机立即绑定

这是测试3个值之间相等性的有效方法吗?

这是测试3个值之间相等性的有效方法吗?

米脂 2021-04-08 18:19:08
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;}在这里,我正在比较一款名为“幸运”的游戏中的死亡情况。如果玩家下注,所有骰子都相同,那么我只需要简单地返回一个支付金额。我主要关注条件陈述中的表达。我想知道这样写是否有效或“好的做法”。
查看完整描述

3 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

是的,它是有效的。的==操作者是可传递的,这意味着A == B和B ==Ç意味着A == C.

因此,我可能会将其写为

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


查看完整回答
反对 回复 2021-04-18
?
RISEBY

TA贡献1856条经验 获得超5个赞

你在做什么很好。也可以为此编写自己的帮助器方法。


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

}

如果您可能需要比较更多的值的用例,这将使您以后更容易阅读。


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


查看完整回答
反对 回复 2021-04-18
?
胡说叔叔

TA贡献1804条经验 获得超8个赞

到目前为止,我看不到您提供的代码有任何问题。


这是您可以对代码进行的一些外观更新。这将使它看起来更简单,并减少行数,并在此过程中还节省了一些内存。


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;

}

PS:如果变量的值three_rolled将始终保持为3,那么我想您可以将其分配给byte或类似的数据类型。不需要adouble这么小的值。更好的内存管理可以带来令人满意的编译器和更干净的代码。


查看完整回答
反对 回复 2021-04-18
  • 3 回答
  • 0 关注
  • 156 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信