3 回答
![?](http://img1.sycdn.imooc.com/5458502c00012d4a02200220-100-100.jpg)
TA贡献1848条经验 获得超10个赞
是的,它是有效的。的==
操作者是可传递的,这意味着A == B和B ==Ç意味着A == C.
因此,我可能会将其写为
if (dice.getFirst() == dice.getSecond() && dice.getSecond() == dice.getThird())
![?](http://img1.sycdn.imooc.com/533e4bec0001ae5302000200-100-100.jpg)
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()) {}
![?](http://img1.sycdn.imooc.com/54584f9d0001219b02200220-100-100.jpg)
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这么小的值。更好的内存管理可以带来令人满意的编译器和更干净的代码。
添加回答
举报