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;
}在这里,我在一个叫做“Chuck-a-luck”的游戏中比较“死亡”。我需要简单地返回一个支付金额,如果玩家已经打赌骰子将全部相同。
我主要关注的是条件语句中的表达式。我想知道这样写是有效的还是“好习惯”。
任何其他建议也是受欢迎的。
发布于 2018-06-20 11:30:39
是的,它是有效的。==运算符是可传递的,这意味着A == B和B == C意味着A == C。
因此,我可能会把它写成
if (dice.getFirst() == dice.getSecond() && dice.getSecond() == dice.getThird())发布于 2018-06-20 11:17:16
你所做的一切都很好。也可以为此编写自己的助手方法。
@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()) {}发布于 2018-06-20 11:26:49
到目前为止,我没有看到您给出的代码有任何问题。
以下是您可以对代码进行的一些表面上的更新。将使它看起来更简单,并减少行数,并在此过程中为您节省一些内存。
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 :如果变量
three_rolled的值始终保持为3,那么我认为您可以将其赋给byte或类似的数据类型。对于这么小的值,不需要double。更好的内存管理带来了令人愉快的编译器和更干净的代码。
https://stackoverflow.com/questions/50939575
复制相似问题