英文:
Find data of a given value and if it doesn't exist then find last entry in series of that value data
问题
我遇到了一个有趣的问题,假设你的数据库中有一张表,包括:月份、年份、利率。
每个月份都有一个条目,用户只能为该月份提交一个条目,而且只能更新现有记录。现在,我需要根据月份和年份获取数据,并且我已经将月份和年份作为参数提供,这两个值都是整数。
假设你需要获取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;
}
请提供你的想法,为什么它会进入无限循环。
英文:
I have interesting question I came across, Let say you have a table in your database that consist: month, year, interest rate.
You've entry for each month and user is limited to make only one entry for the month and you can just update the existing record. Now, I need to get data by month and year and I have given month and year as parameter and both values are in int.
Suppose you've to get data of 6 month and you don't have entry for that month then you need to return 5 month's data and if that also doesn't exists and so on.
I have tried recursion but that also go under stack overflow exception.
Here is the sample method that I've written please suggest yours:
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;
}
Please suggest your thoughts why it's going in infinite loop
答案1
得分: 1
你在使用后缀方式减少 givenMonth
在你的递归方法调用中。因此,你使用未改变的 givenMonth
值调用了你的递归方法 getCurrentRateOrLastEntry
。终止条件 if(givenMonth <= 0)
永远不会被触发。使用前缀方式减少 givenMonth
-> --givenMonth
。
英文:
You are using postfix to decrease givenMonth
at your recursive method call. So you call your recursive method getCurrentRateOrLastEntry
with unchanged givenMonth
value. The termination condition if(givenMonth <= 0)
is never triggered. Use prefix to decrease givenMonth
-> --givenMonth
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论