The first free response of the 2019 AP exam has you working with an arbitrary class for working with dates called APCalendar
.
For this we’re going to be implementing two methods, numberOfLeapYears
and dayOfWeek
.
There are also three helper methods called firstDayOfYear
, dayOfYear
and isLeapYear
. Since they’re giving you the helper methods, it’s almost guaranteed that you’ll be calling them somewhere from your solution. And, in face the explanations for the two methods you’re implementing note that calling these helpers is required.
For Part A we’re counting the number of leap years between year1
and year2
, inclusive. And we’re going to use the isLeapYear
helper to make it easier. isLeapYear
returns true
if a year is a leap year and false
if not.
public static int numberOfLeapYears(int year1, int year2) {
int cnt = 0;
for (int y=year1; y<=year2; y++) {
if (isLeapYear(y)) {
cnt++;
}
}
return cnt;
}
What I’m doing is creating a counter variable to hold the number of leap years.
Then, a for loop takes the code through all the years from year1
to year2
, inclusive (note the y <= year2
). The isLeapYear
method is called on year year, and if it’s a leap year the code increments cnt
.
cnt
is returned at the end as the count of leap years.
Part B asks us to implement a method that calculates what day of the week any given date falls on.
The help we have two helper methods.
firstDayOfYear
returns an integer that represents what day of the week a specific date is. Sunday is represented by 0, Monday by 1, and so on through Saturday which is represented by 6.
dayOfYear
tells us what day a date fallse on. For example, dayOfYear( 1, 5, 2019 )
would return 5
because the 5th of January is the fifth day of the year in 2019.
public static int dayOfWeek(int month, int day, int year) {
int firstDay = firstDayOfYear(year);
int doy = dayOfYear(month, day, year);
return (firstDay + doy - 1) % 7;
}
I’m storing both the first day of the year and the day of the year in variables firstDay
and doy
.
Adding those two values together, and subtracting 1 because dayOfWeek
should return based on a 0-indexed array instead of the 1-based list of days, gives us the right day of the week. The % 7
at the end takes care of keeping the value within the bounds of the day of week index.