I have to create my own calendar class (I know one exists, but we're being tested on our class creating skills, so I can't use any existing methods from the existing calendar class). One of the methods we have to provide is the ability to roll the Calendar date forward or backwards by a given number of months.
Firstly, my constructor for a Calendar object takes a day, month, and year value. The values are then validated (e.g. makes sure given days is within the number of days in the given month, makes sure months is between 1 and 12).
Now, for the roll back method, I've written this:
public void rollMonths(int m) {
if(month + m > 12){ // Checks if the given months plus the current month will need to increase the year
year = year + 1; // Increases the year by one if it goes over.
month = m - (12 - month); } // Finds the number of months till the end of the year, and subtracts this from the given months. Then sets the month to the new value.
else if(month + m < 0) { // Checks if the year will need to be decreased.
year = year - 1; // Decreases the year by 1;
month = 12 - (Math.abs(m) - month); } // Finds the months between the start of the year and the current month, and subtracts this from the given month value. Then sets the month to this value.
else
month 开发者_Go百科= month + m; // If current month plus given months is within the same year, adds given months to current month.
}
This method works, but only if the calendar doesn't increase by more than one year. For example, if I have a calendar for august 2011, and I roll forward 6 months, I correctly get February 2012. However, if I try to roll forward 20 months, the month becomes 16.. Similarly for when I try to roll back a given number of months. I get a correct answer when rolling back within one year.
Sorry if that didn't seem to make sense, I'm not too sure how to explain it. If it doesn't let me know and I'll try to write a better explanation.
Clearly a homework, so i'll just point out the flaw...
Here's you're problem
if(month + m > 12){ // Checks if the given months plus the current month will need to increase the year
year = year + 1; // Increases the year by one if it goes over.
month = m - (12 - month); }
You're incrementing year by just 1
year, no matter how many months we are adding...it could be 20,40 or whatever...
Years will increase by m/12
and months will increase by whatever is left after subtracting the years.
Hint: You'll need to use the Mod
operator.
First, you can use implementations of Calendar such as GregorianCalendar.
You need a loop to keep the month number valid. Something like this:
month += m;
while(month < 1){
month += 12;
year -= 1;
}
while(month > 12){
month -= 12;
year += 1;
}
Alternatively, you can do it in one go:
month += m;
if(month < 1)
year -=1;
if(month > 12 || month < 1){
month = month % 12 + 1;
year += month / 12;
}
精彩评论