首页 > 解决方案 > 查找给定值的数据,如果不存在,则查找该值数据系列中的最后一个条目

问题描述

我遇到了一个有趣的问题,假设您的数据库中有一个表,其中包含:月、年、利率。

您每个月都有条目,用户仅限于每个月输入一个条目,您可以只更新现有记录。现在,我需要按月和年获取数据,并且我将月份和年份作为参数,并且两个值都在 int 中。

假设您要获取 6 个月的数据并且您没有该月的条目,那么您需要返回 5 个月的数据,如果该数据也不存在,依此类推。

我已经尝试过递归,但这也受到堆栈溢出异常的影响。

这是我编写的示例方法,请建议您的方法:

private InterestRate getCurrentRateOrLastEntry(int month, int year) {
        int givenMonth = month;
        if(givenMonth <= 0) {
            return null;
        }
        InterestRate cost = InterestRateRepo.findByMonthAndIsDeletedAndYear(month, false, year);
        return (cost == null) ?  getCurrentRateOrLastEntry(givenMonth--, year): cost;
    }

请提出您的想法,为什么它会无限循环

标签: javaspringalgorithmspring-boot

解决方案


您正在使用后缀来减少givenMonth递归方法调用。getCurrentRateOrLastEntry所以你用不变的givenMonth值调用你的递归方法。if(givenMonth <= 0)永远不会触发终止条件。使用前缀减少givenMonth-> --givenMonth


推荐阅读