Exercise : ZuneBug

The following code from Microsoft's Zune music player calculates today's date from the years/days passed since 1980. But all Zune players locked up on Dec 31 2008. Why? Download icon ZuneBug.java and modify it to fix the bug.

int days = getTotalDaysSince1980();   // pretend this method exists
int year = 1980;
while (days > 365) {                  // subtract out years
    if (isLeapYear(year)) {           // pretend this method exists
        if (days > 366) {
            days = days - 366;
            year++;
        }
    } else {
        days = days - 365;
        year++;
    }
}
  

Exercise : ZuneBug - answer

The bug occurs when the current year is a leap year and there are exactly 366 days left (i.e., if today is Jan 1 on a year after a leap year). The code gets stuck in an infinite loop with days == 366 because the while test is true but the if (days > 366) is false. Here is a fixed version:

int days = getTotalDaysSince1980();   // pretend this method exists
int year = 1980;
while (days > 365 || (isLeapYear(year) && days > 366)) {
    if (isLeapYear(year)) {
        days = days - 366;
    } else {
        days = days - 365;
    }
    year++;
}