Java根据范围取值

题目:假设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));
            }
        }
    }
}

结果示例
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值