public static double calculateMinPayment(double newBalance) {
double x;
if (newBalance < 0.00) {
return 0.00;
} else if (newBalance > 0.00 && newBalance <= 49.99) {
x = newBalance;
} else if (newBalance >= 50.00 && newBalance <= 300) {
x = 50.00;
} else {
x = newBalance * 0.2;
}
return x;
}
我不能使用&&或者||,如果没有这些操作符,我如何能够格式化相同的代码?
因为你的条件是不断增加的,没有空格,你不需要任何and条件,比较可以很直接。
public static double calculateMinPayment(double newBalance) {
double x;
if (newBalance < 0.0) {
return 0.0;
} else if (newBalance < 50.0) {
return newBalance;
} else if (newBalance <= 300.0) {
return 50.0;
} else {
return newBalance * 0.2;
}
}
一个小的变化是跳过所有的else
,因为我们使用return
if (newBalance < 0.0) {
return 0.0;
}
if (newBalance < 50.0) {
return newBalance;
}
if (newBalance <= 300.0) {
return 50.0;
}
return newBalance * 0.2;
您可以像下面这样使用嵌套的
if
语句:
public static double calculateMinPayment(double newBalance) {
double x;
if (newBalance < 0.00) {
return 0.00;
} else if (newBalance > 0.00) {
if (newBalance <= 49.99) {
x = newBalance;
} else if (newBalance >= 50.00) {
if (newBalance <= 300) {
x = 50.00;
} else {
x = newBalance * 0.2;
}
} else {
x = newBalance * 0.2;
}
} else {
x = newBalance * 0.2;
}
return x;
}
要完全避免写入if
,您可以执行以下操作。LinkedHashMap
跟踪所有条件以及如果条件为true
时返回的结果。因为它是LinkedHashMap
,所以计算条件的顺序是它们在映射中的顺序,类似于编写if
循环的顺序。
逻辑返回第一个条件的结果true
任何新条件都可以简单地添加到LinkedHashMap
中,在与您想要计算的顺序相等的位置
private static double calculateMinPayment(final double newBalance) {
LinkedHashMap<Predicate<Double>, Function<Double, Double>> conditionResult = new LinkedHashMap<>();
conditionResult.put(balance -> balance < 0.0, balance -> 0.0);
conditionResult.put(balance -> balance < 50.0, balance -> balance);
conditionResult.put(balance -> balance < 300.0, balance -> 50.0);
double minPayment = conditionResult.entrySet()
.stream()
.filter(entry -> entry.getKey().test(newBalance))
.findFirst()
.map(entry -> entry.getValue().apply(newBalance))
.orElse(newBalance * 0.2);
return minPayment;
}