public class Calendar {
public static void main(String[] args) {
System.out.println("Input year pleas : ex) 2013");
System.out.print(">> ");
Scanner scanner = new Scanner(System.in);
int year = Integer.parseInt(scanner.nextLine());
new Year(year).print();
}
}
public class Month {
private int month;
private int length;
private int startDate; // 1:mon 2:tue 3:wed 4:thu 5:fri 6 :sat 0:sun
public Month(int month, int length, int startDate) {
this.month = month;
this.length = length;
this.startDate = startDate;
}
public void print() {
System.out.println("MONTH : " + month);
System.out.println("sun mon tue wed thu fri sat");
String days = "";
for (int i = 1; i <= startDate; i++) {
days += "\t";
}
for (int i = 1; i <= length; i++) {
days += i;
days += ((i + startDate) % 7 == 0 ? "\n" : "\t");
}
System.out.println(days + "\n");
}
}
public class Year {
private int year;
private List<Month> months;
public Year(int year) {
this.year = year;
setMonths();
}
private void setMonths() {
months = MonthFactory.getMonths(year);
}
public void print() {
System.out.println("THIS YEAR IS : " + year + "\n\n");
for (Month m : months) {
m.print();
}
}
}
public class MonthFactory {
public static List<Month> getMonths(int year) {
List<Month> months = new ArrayList();
for (int i = 1; i <= 12; i++) {
months.add(new Month(i, getDaysOfMonth(year, i), getStartDate(year, i)));
}
return months;
}
public static int getDaysOfYear(int year) {
return isLeap(year) ? 366 : 365;
}
public static int getDaysOfMonth(int year, int month) {
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10: case 12:
return 31;
case 4: case 6: case 9: case 11:
return 30;
case 2:
return (isLeap(year) ? 29 : 28);
default:
return 0;
}
}
public static boolean isLeap(int year) {
return (year % 400 == 0) || (year % 4 == 0) && (year % 100 != 0);
}
public static int getStartDate(int year, int month) {
int totalDays = 0;
for (int i = 1; i < year; i++) { // add days of years
totalDays += getDaysOfYear(i);
}
for (int i = 1; i < month; i++) { // add days of months
totalDays += getDaysOfMonth(year, i);
}
return (totalDays + 1) % 7; // +1 for sunday
}
}