Skip to content

Commit d7c5e54

Browse files
committed
Made a class of printing the calendar.
1 parent 34d6268 commit d7c5e54

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

src/practice/CalendarClass.java

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package practice;
2+
3+
import java.util.Calendar;
4+
5+
public class CalendarClass {
6+
7+
// DATE와 DAY_OF_MONTH는 같다.
8+
private Calendar cal = null;
9+
// 요일 표시
10+
private String[] header = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
11+
12+
private int startDayOfWeek; // 해당 월의 시작 요일 (SUN: 1, ... , SAT: 7)
13+
private int endDate; // 해당 월의 마지막 날짜
14+
private int tableRows; // 해당 월의 주 개수
15+
private int tableCols = header.length;
16+
private int year;
17+
private int month;
18+
19+
public CalendarClass(int year, int month) throws Exception {
20+
21+
// AD 1년부터 시작한다
22+
if(year < 1) {
23+
this.year = 1;
24+
} else {
25+
this.year = year;
26+
}
27+
28+
// month 값의 범위는 1 ~ 12으로 제한한다
29+
if(month < 1 || month > 12) {
30+
throw new Exception("month에는 1 ~ 12의 값만 들어갈 수 있습니다.");
31+
} else {
32+
// parameter로 받은 year, month와 date를 세팅한다
33+
this.month = month;
34+
cal = Calendar.getInstance();
35+
cal.set(Calendar.YEAR, this.year);
36+
cal.set(Calendar.MONTH, this.month - 1);
37+
cal.set(Calendar.DATE, 1);
38+
39+
tableRows = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
40+
startDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
41+
endDate = cal.getActualMaximum(Calendar.DATE);
42+
}
43+
44+
}
45+
46+
public void printCalendar() {
47+
48+
// year, month를 출력한다
49+
System.out.printf("%10d년 %5d월\r\n", year, month);
50+
51+
// day of week를 출력한다
52+
for(int i=0; i<header.length; i++) {
53+
System.out.printf("%s ",header[i]);
54+
}
55+
System.out.println();
56+
57+
// date를 출력한다
58+
int date = 1;
59+
outer_loop:
60+
for(int i=0; i<tableRows; i++) {
61+
for(int j=0; j<tableCols; j++) {
62+
63+
if( i == 0 && j < (startDayOfWeek - 1) ) {
64+
// 시작 요일 전까지는 공백을 출력한다
65+
System.out.printf("%3s ", "");
66+
} else {
67+
System.out.printf("%3s ", date + "");
68+
69+
if(date == endDate) {
70+
// 해당 월의 마지막 날짜에 다다르면 입력을 종료한다
71+
break outer_loop;
72+
}
73+
date++;
74+
}
75+
}
76+
System.out.println();
77+
}
78+
79+
}
80+
81+
public static void main(String[] args) throws Exception {
82+
83+
CalendarClass cal = new CalendarClass(2020, 2);
84+
cal.printCalendar();
85+
86+
}
87+
}

0 commit comments

Comments
 (0)