我有这个非常长的if和else声明,任何想法我怎么能缩短这个?
或者这是我处理这个问题的唯一方法吗?
if (HR < 41) {
HR_Score = 2;
} else if (HR < 51) {
HR_Score = 1;
} else if (HR < 101) {
HR_Score = 0;
} else if (HR < 111) {
HR_Score = 1;
} else if (HR < 129) {
HR_Score = 2;
} else {
HR_Score = 3;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用NavigableMap解决您的问题.例如:
// In the class
private static final NavigableMap<Integer, Integer> map = new TreeMap<>();
map.put(41, 2);
map.put(51, 1);
map.put(101, 0);
map.put(111, 1);
map.put(129, 2);
map.put(Integer.MAX_VALUE, 3);
// When you need a score
HR_Score = map.ceilingEntry(HR).getValue();
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用? :运算符使代码更短:
int HR_Score = HR < 41 ? 2 :
(HR < 51) ? 1 :
(HR < 101) ? 0 :
(HR < 111) ? 1 :
(HR < 129) ? 2 :
3;
Run Code Online (Sandbox Code Playgroud)
条件运算符(又名“三元”,因为它需要三个操作数)是链接您不想嵌套的 if/else 语句的便捷方式。