[英]Java - Can I simplify this code using Recursion or any other methods?
So I have this method, roosterID is for generating an ID based on the current year and week of year, this is what I've come up with, but I don't think this is the best way to do it, I tried making the method recursive at some point. 所以我有这种方法,roosterID是用于根据当前年份和年份生成ID,这是我想出的方法,但是我认为这不是最好的方法,我尝试过该方法在某些时候是递归的。 That didn't work the way I wanted it to.
那不是我想要的那样工作。 At least, the way I tried it.
至少,我尝试过的方式。 Basically say there's a year that has 53 weeks, I'm calling the load method of rDAO, with the roosterID for the current week, and the 2 coming weeks.
基本上说一年有53个星期,我叫rDAO的load方法,其中包含本周的roosterID和接下来的2周。 Basically I want the roosterID to be 20141 for the week after 201353, simply using roosterID+1 would make it 201354. I hope my explanation isn't to rubbish.
基本上,我希望roosterID在201353之后的那一周是20141,仅使用roosterID + 1就可以使其成为201354。我希望我的解释不是垃圾。
the code below works, I just think it's kind of dirty and unprofessional, and can be done a lot better, if anything changes I have to redo pretty much all the code, so i'd like some advice. 下面的代码有效,我只是认为这有点脏而且不专业,可以做得更好,如果有任何更改,我必须重做几乎所有代码,所以我想提出一些建议。
public void getWeekTabs(){
gc.setFirstDayOfWeek(Calendar.MONDAY);
if(gc.get(Calendar.WEEK_OF_YEAR) <= gc.getWeeksInWeekYear()-2){
roosterID = Integer.parseInt(Integer.toString(gc.get(Calendar.YEAR)) + Integer.toString(gc.get(Calendar.WEEK_OF_YEAR)));
rDAO.load(roosterID);
rDAO.load(roosterID +1);
rDAO.load(roosterID +2);
}else if(gc.get(Calendar.WEEK_OF_YEAR) == gc.getWeeksInWeekYear()-1){
roosterIDtemp = Integer.parseInt(Integer.toString(gc.get(Calendar.YEAR) +1 ) + Integer.toString(1));
rDAO.load(roosterID);
rDAO.load(roosterID +1);
rDAO.load(roosterIDtemp);
}else if(gc.get(Calendar.WEEK_OF_YEAR) == gc.getWeeksInWeekYear()){
roosterIDtemp = Integer.parseInt(Integer.toString(gc.get(Calendar.YEAR) +1 ) + Integer.toString(1));
rDAO.load(roosterID);
rDAO.load(roosterIDtemp);
rDAO.load(roosterIDtemp +1);
}
}
First of all, this is weird: 首先,这很奇怪:
roosterID = Integer.parseInt(Integer.toString(gc.get(Calendar.YEAR)) + Integer.toString(gc.get(Calendar.WEEK_OF_YEAR)));
Do this: 做这个:
public String makeRoosterId(Calendar gc) {
return String.format("%d%d", gc.get(Calendar.YEAR), gc.get(Calendar.WEEK_OF_YEAR));
}
If you want 201401 instead of 20141, you can modify the format expression to do that. 如果要使用201401而不是20141,则可以修改格式表达式来执行此操作。 Now, to load your three items:
现在,加载您的三个项目:
Calendar c = Calendar.getInstance(); // current date
rDAO.load(makeRoosterId(c)); // Load this week
c.add(Calendar.WEEK_OF_YEAR, 1);
rDAO.load(makeRoosterId(c)); // Load next week
c.add(Calendar.WEEK_OF_YEAR, 1);
rDAO.load(makeRoosterId(c)); // Load the week after that
That should do it. 那应该做。
EDIT : See comments about issues that happen at year boundaries. 编辑 :查看有关在年份边界发生的问题的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.