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

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;


}

在这里,我正在比较一款名为“幸运”的游戏中的死亡情况。如果玩家下注,所有骰子都相同,那么我只需要简单地返回一个支付金额。


我主要关注条件陈述中的表达。我想知道这样写是否有效或“好的做法”。


米脂
浏览 157回答 3
3回答

慕桂英546537

是的,它是有效的。的==操作者是可传递的,这意味着A == B和B ==Ç意味着A == C.因此,我可能会将其写为if (dice.getFirst() == dice.getSecond() && dice.getSecond() == dice.getThird())

RISEBY

你在做什么很好。也可以为此编写自己的帮助器方法。@SafeVarargspublic static final boolean equals(Object... objs) {&nbsp; &nbsp; if (objs== null || objs.length < 2) return false; // You may return true or throw exception&nbsp; &nbsp; for (int i = 0; i < nums.length - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (!Objects.equals(objs[i], objs[i + 1])) return false;&nbsp; &nbsp; }&nbsp; &nbsp; return true;}如果您可能需要比较更多的值的用例,这将使您以后更容易阅读。&nbsp;if (Helper.equals(dice.getFirst(), dice.getSecond(), dice.getThird()) {}

胡说叔叔

到目前为止,我看不到您提供的代码有任何问题。这是您可以对代码进行的一些外观更新。这将使它看起来更简单,并减少行数,并在此过程中还节省了一些内存。public static double tripleBet(Dice dice, double betAmount) {&nbsp; &nbsp; double three_rolled = 3;&nbsp; &nbsp; // Using Ternary Operator we eliminated the need for a separate variable "payout" by simple returning the resultant values to the caller method.&nbsp; &nbsp; return (dice.getFirst() == dice.getSecond() && dice.getThird() == dice.getFirst()) ? betAmount * three_rolled : -betAmount;}PS:如果变量的值three_rolled将始终保持为3,那么我想您可以将其分配给byte或类似的数据类型。不需要adouble这么小的值。更好的内存管理可以带来令人满意的编译器和更干净的代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java