Skip to content

Instantly share code, notes, and snippets.

@tangingw
Last active November 11, 2020 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangingw/687e0a656b85faf98867a8b1e4c9519d to your computer and use it in GitHub Desktop.
Save tangingw/687e0a656b85faf98867a8b1e4c9519d to your computer and use it in GitHub Desktop.
Answer for Creative Exercise 2.1.30 at https://introcs.cs.princeton.edu/java/21function/
public class Calendar {
public static int getDayOfWeek(int day, int month, int year) {
int monthTemp = (14 - month) / 12;
int y0 = year - monthTemp;
int x = y0 + (y0 / 4) - (y0 / 100) + (y0 / 400);
int m0 = month + (12 * monthTemp) - 2;
int d0 = (day + x + (31 * m0 / 12)) % 7;
return d0;
}
public static String getMonthStr(int month) {
String[] monthStr = {
"January", "February", "March", "April", "May",
"June", "July", "August", "September",
"October", "November", "December"
};
return monthStr[month - 1];
}
public static boolean checkLeapYear(int year) {
boolean isLeapYear;
isLeapYear = year % 4 == 0;
isLeapYear = isLeapYear && (year % 100 != 0);
isLeapYear = isLeapYear || (year % 400 == 0);
return isLeapYear;
}
public static int getDaysMonth(int month, int year) {
int[] daysMonth = {31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (checkLeapYear(year)) {
daysMonth[1] = 29;
} else {
daysMonth[1] = 28;
}
return daysMonth[month - 1];
}
public static void printHeader(int month, int year) {
System.out.println(" " + getMonthStr(month) + " " + year);
System.out.println(" Su Mo Tu We Th Fr Sa");
}
public static void main(String[] argv) {
int month = Integer.parseInt(argv[0]);
int year = Integer.parseInt(argv[1]);
int dayCount = 1;
int dayInMonth = getDaysMonth(month, year);
printHeader(month, year);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (getDayOfWeek(dayCount, month, year) == j && dayCount <= dayInMonth) {
System.out.printf(" %2d", dayCount);
dayCount++;
} else {
System.out.printf(" %2s", " ");
}
}
System.out.println(" ");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment