题目:假设2021年为202109-202204,2022年为202205-202209,根据输入判断输入年月属于何年,不在范围则返回null。
解答:
1.根据NavigableMap建立RangeMap范围映射类
class RangeMap<K,V> {
private final NavigableMap<K, V> map = new TreeMap<>();
public void put(K start, K end, V value) {
map.put(start, value);
map.put(end, value);
}
public V get(K key) {
if (key == null || map.ceilingKey(key) == null || map.floorKey(key) == null) {
return null;
}
return map.get(map.ceilingKey(key)).equals(map.get(map.floorKey(key))) ? map.get(map.ceilingKey(key)) : null;
}
}
2.编写客户端代码
public class Test02 {
public static void main(String[] args) {
// 范围数据
RangeMap<String, String> map = new RangeMap<>();
map.put("202109", "202204", "2021");
map.put("202205", "202301","2022");
// 输入
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
System.out.print("请输入月份:");
String month = sc.nextLine();
if ("q".equals(month)) {
break;
} else {
System.out.println(map.get(month));
}
}
}
}
结果示例