java - 这个 else if 语句有更好的结构吗?
问题描述
我正在尝试在这里构建一个语句,并且对我们从条件中获得的值和结果if else
感到有些困惑。return
boolean
在这种情况下是否有可能有两个语句return true
或者它会在第一个块之后退出?
有没有更好的方法来写这个?(也许使用一个switch
?)
此代码适用于支票账户的提款。我希望它符合以下规则:
- 如果要提取的金额为 == 或 < 0,则返回 false。
- 如果要提取的金额 > 0,则返回 true。
- 如果要提取的金额>余额,则检查并返回true。(但只有一次,因为我只想让一个帐户透支一次。)
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;
}
}
解决方案
该方法将在第一次遇到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>
推荐阅读
- css - 如何在一个之后显示元素
,在屏幕内? - php - Laravel:如何从 API 获取 json 响应
- r - 在R中将浮点数转换为字符串而不会丢失精度
- angular - Stackblitz:如何使用 Angular 执行测试?
- uwp-xaml - XAML 错误但不是
- active-directory - LDAP 无效凭据 - Active Directory Windows Server 2012 R2
- r - 通过另一个数据帧的两列中的值对两个数据帧中的数据帧进行子集
- matrix - Xcode simd - 平移和旋转矩阵示例的问题
- javascript - d3js v5 + topojson v3 在后台访问对象的属性
- cassandra - 如何在 Cassandra 中设计一个包含事件日期和四列过滤的表格