FRQ
a) Write the static method numberOfLeapYears, which returns the number of leap years between year1 and year2, inclusive. In order to calculate this value, a helper method is provided for you. • isLeapYear(year) returns true if year is a leap year and false otherwise. Complete method numberOfLeapYears below. You must use isLeapYear appropriately to receive full credit. /** Returns the number of leap years between year1 and year2, inclusive.
- Precondition: 0 <= year1 <= year2 */ public static int numberOfLeapYears(int year1, int year2)
public static int numberOfLeapYears(int year1, int year2) {
for (int y=year1; y<=year2; y++)
// The helper method "isLeapYear(y)"returns true given an input of a leap year and false given the input of a non-leap year.
if (isLeapYear(y)) {
count++;
}
}
return count;
}
The Method "numberOfLeapYears" outputs the number of leap years that there are between a certain set of years. The helper method "isLeapYear(y)" is the main part of this function and returns true given an input of a leap year and false given the input of a non-leap year.
1b) Write the static method dayOfWeek, which returns the integer value representing the day of the week for the given date (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. For example, 2019 began on a Tuesday, and January 5 is the fifth day of 2019. As a result, January 5, 2019, fell on a Saturday, and the method call dayOfWeek(1, 5, 2019) returns 6. As another example, January 10 is the tenth day of 2019. As a result, January 10, 2019, fell on a Thursday, and the method call dayOfWeek(1, 10, 2019) returns 4. In order to calculate this value, two helper methods are provided for you. • firstDayOfYear(year) returns the integer value representing the day of the week for the first day of year, where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. For example, since 2019 began on a Tuesday, firstDayOfYear(2019) returns 2. • dayOfYear(month, day, year) returns n, where month, day, and year specify the nth day of the year. For the first day of the year, January 1 (month = 1, day = 1), the value 1 is returned. This method accounts for whether year is a leap year. For example, dayOfYear(3, 1, 2017) returns 60, since 2017 is not a leap year, while dayOfYear(3, 1, 2016) returns 61, since 2016 is a leap year.
public static int dayOfWeek(int month, int day, int year) {
int firstDay = firstDayOfYear(year);
int day = dayOfYear(month, day, year);
//subtract one because the calendar doesn't start at 0
return (firstDay + day - 1) % 7;
}
The method firstDayOfYear outputs a value that shows what day of the week a date on the calendar is. Sunday is represented by a value of zero, Monday by one, up until Saturday which is represented by six.
The methoddayOfYear tells us what day a certain calendar date on. For example, dayOfYear( 7, 6, 2011 ) would return 6 because the 6th of January is the sixth day of the year in 2011.