首页 > 解决方案 > 这个 else if 语句有更好的结构吗?

问题描述

我正在尝试在这里构建一个语句,并且对我们从条件中获得的值和结果if else感到有些困惑。returnboolean

在这种情况下是否有可能有两个语句return true或者它会在第一个块之后退出?

有没有更好的方法来写这个?(也许使用一个switch?)

此代码适用于支票账户的提款。我希望它符合以下规则:

public boolean withdraw(double amount) {

//amount = amount of money asked to be withdrawn

    if (amount > balance) {
        setBalance(balance - amount - overdraftFee);
        return true;
    } else if (amount == 0) {
        System.out.println("Withdrawal amount cannot be $0.00!");
        return false;
    } else if (amount < 0) {
        System.out.println("Withdrawal amount cannot be a negative amount!");
        return false;
    } else {
        setBalance(balance - amount);
        return true;
    }
}

标签: javaif-statement

解决方案


该方法将在一次遇到return. else这样做的一个副作用是,如果块将在块中返回,则您不需要使用块if(因为该块之后的所有内容只有在条件为 时才会运行false)。

更重要的double是,在 Java 中用于货币金额不是一个好的选择,并且会导致代码中的舍入错误(我将在代码块之后进行更多解释)。更好的选择是BigDecimal

另一种写法是:

public boolean withdraw(BigDecimal amount) {

    if (BigDecimal.ZERO.equals(amount)) {
        System.out.println("Withdrawal amount cannot be $0.00!");
        return false;
    }

    if (BigDecimal.ZERO.compareTo(amount) < 0) {
        System.out.println("Withdrawal amount cannot be a negative amount!");
        return false;
    }

    BigDecimal feeToCharge = (this.balance.compareTo(amount) < 0) ? this.overdraftFee : BigDecimal.ZERO;

    setBalance(this.balance.minus(amount).minus(feeToCharge));
    return true;

}

使用BigDecimal而不是double用于货币的原因是由于内部表示双精度的方式,并非所有十进制数字都可以准确存储。这会导致舍入错误,这对货币很重要。例如,以下测试失败:

    @Test
    public void testDoubleSubtraction() {
        assertThat(0.3D - 0.1D, is(0.2D));
    }

有错误

java.lang.AssertionError: 
Expected: is <0.2>
     but: was <0.19999999999999998>

推荐阅读