需要替换多个独立的if语句
我是 Java 的初学者,我有一个健康保险计划,该计划根据客户是否已经存在任何健康状况返回总报价。每个健康状况将总量增加不同的百分比,并且可能存在多个健康状况,在这种情况下,总量将根据 if 语句的顺序增加。例如,客户可能有“骨髓”,在这种情况下,总数乘以 20%,或者他们可能有“骨髓”和“癌症”,在这种情况下,总数增加 20%,然后在那个命令。
我用多个独立的 if 语句写了这个,因为与 if else 语句不同,可能存在多个健康状况。有没有一种方法可以让我以一种比一长串 if 语句更优雅的方式来编写它?
if (customer.getHealthConditions().equals("Bone Marrow")) {
total *= 1.2;
}
if (customer.getHealthConditions().equals("Cancer")) {
total *= 1.25;
}
if (customer.getHealthConditions().equals("Cardiovascular Disease")) {
total *= 1.3;
}
if (customer.getHealthConditions().equals("Gastrointestinal")) {
total *= 1.1;
}
if (customer.getHealthConditions().equals("Infections")) {
total *= 1.1;
}
if (customer.getHealthConditions().equals("Kidneys")) {
total *= 1.25;
}
if (customer.getHealthConditions().equals("Lungs")) {
total *= 1.25;
}
if (customer.getHealthConditions().equals("Musculoskeletal")) {
total *= 1.3;
}
回答
switch在这种情况下,这种说法似乎更合适:
double quotient = 1.0;
switch(customer.getHealthConditions()) {
case "Bone Marrow":
quotient = 1.2; break;
case "Cancer":
case "Kidneys":
case "Lungs":
quotient = 1.25; break;
case "Cardiovascular Disease":
case "Musculoskeletal":
quotient = 1.3; break;
case "Gastrointestinal":
case "Infections":
quotient = 1.1; break;
}
total *= quotient;
在 Java 12+ 中,switch语句增强了多个 case 和箭头,->因此它可以写为:
total *= switch(customer.getHealthConditions()) {
case "Bone Marrow" -> 1.2;
case "Cancer", "Kidneys", "Lungs" -> 1.25;
case "Cardiovascular Disease", "Musculoskeletal" -> 1.3;
case "Gastrointestinal", "Infections" -> 1.1;
default -> 1.0;
}
更新
如果健康状况是多重的,那么equals根本不适用,而是应该使用String::contains或Collection::contains应该使用,最好有疾病的地图或枚举来商数:
Map<String, Double> quotients = Map.of(
"Bone Marrow", 1.2,
"Cancer", 1.25,
"Kidneys", 1.25,
"Lungs", 1.25
// ...
);
total *= quotients.entrySet().stream()
.filter(e -> customer.getHealthConditions().contains(e.getKey()))
.map(Map.Entry::getValue)
.reduce(1.0, (p, v) -> p * v);