题目
完成该功能,根据账单和服务的总金额计算您需要提示的数量。
您需要考虑以下评级:
- Terrible可怕: tip小费 0%
- Poor差: tip 5%
- Good好: tip 10%
- Great太棒了: tip 15%
- Excellent优秀: tip 20%
评级不区分大小写(所以"great" = "GREAT")。如果收到无法识别的评级,则需要返回:
- 在Java中返回......或者null
因为你是一个好人,无论服务如何,你总是围绕小费。
解题
My:
public class TipCalculator {
public static Integer calculateTip(double amount, String rating) {
double n = 0;
if ("terrible".equals(rating.toLowerCase())) {
n = 0;
} else if ("poor".equals(rating.toLowerCase())) {
n = 0.05;
} else if ("good".equals(rating.toLowerCase())) {
n = 0.1;
} else if ("great".equals(rating.toLowerCase())) {
n = 0.15;
} else if ("excellent".equals(rating.toLowerCase())) {
n = 0.20;
} else {
return null;
}
return (int)Math.ceil(n * amount); // 向上取整并强制转换int
}
}
Other:
public class TipCalculator {
public static Integer calculateTip(double amount, String rating) {
switch(rating.toLowerCase()) {
case "terrible": return 0;
case "poor": return (int) Math.ceil(amount * 0.05);
case "good": return (int) Math.ceil(amount * 0.1);
case "great": return (int) Math.ceil(amount * 0.15);
case "excellent": return (int) Math.ceil(amount * 0.2);
default: return null;
}
}
}
import java.util.HashMap;
import java.util.Map;
public class TipCalculator {
private static Map<String, Integer> tips = new HashMap<>();
static {
tips.put("terrible", 0);
tips.put("poor", 5);
tips.put("good", 10);
tips.put("great", 15);
tips.put("excellent", 20);
}
public static Integer calculateTip(double amount, String rating) {
Integer tipRating = tips.get(rating.toLowerCase());
if (tipRating == null) return null;
return (int) Math.ceil(tipRating * amount / 100);
}
}
后记
用字典也挺不错的样子。
网友评论