java - 查找给定值的数据,如果不存在,则查找该值数据系列中的最后一个条目
问题描述
我遇到了一个有趣的问题,假设您的数据库中有一个表,其中包含:月、年、利率。
您每个月都有条目,用户仅限于每个月输入一个条目,您可以只更新现有记录。现在,我需要按月和年获取数据,并且我将月份和年份作为参数,并且两个值都在 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;
}
请提出您的想法,为什么它会无限循环
解决方案
您正在使用后缀来减少givenMonth
递归方法调用。getCurrentRateOrLastEntry
所以你用不变的givenMonth
值调用你的递归方法。if(givenMonth <= 0)
永远不会触发终止条件。使用前缀减少givenMonth
-> --givenMonth
。
推荐阅读
- ssl - HTTP/2 必须使用 TLS 吗?
- json - 使用 JSON 的时间序列数据可视化
- powershell - Powershell 2.0 从 zip 中提取某些文件(包括子目录)
- javascript - 画布绘图在外部 .js 文件中不起作用
- python - 如何使用此 CFG 随机生成字符串?
- azure - 在 Azure python 烧瓶应用中安装 pymongo
- vue.js - Vue过滤重新调整数组中的所有对象,即使它们不匹配搜索条件
- java - 尽管有分隔符,为什么我的 parser.next 扫描仪仍选择括号和数字而不是 i 之前的字符串
- python - TypeError: 使用 pisa.Createpdf 时 -: 'str' 和 'int' 不支持的操作数类型
- android - Android:如何使用协程从互联网上读取文件?