java-14: 달력메서드
-MycalendarMethod-
// 달력 작업에 사용할 메소드가 저장된 클래스
public class MyCalendarMethod {
// 인수로 년도를 넘겨받아 윤년, 평년을 판단해 윤년이면 true, 평년이면 false를 리턴하는 메소드
public static boolean isLeapYear(int year) {
return year % 4 == 0 && year % 100 !=0 || year % 400 == 0;
}
// 인수로 년, 월을 넘겨 받아 그달의 마지막 날짜를 리턴하는 메소드
public static int lastDay(int year, int month) {
int[] m = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
m[1] = isLeapYear(year) ? 29 : 28;
return m[month-1];
}
// 인수로 년, 월, 일을 넘겨 받아 1년 1월 1일부터 지나온 날짜의 합계를 계산해 리턴하는 메소드
public static int totalDay(int year, int month, int day) {
int sum = (year-1)*365 + ((year-1) / 4) - ((year-1) /100) + ((year-1) / 400);
for (int i = 1 ; i<month ; i++) {
sum += lastDay(year, i);
}
return sum + day;
}
// 인수로 년, 월, 일을 넘겨받아 요일을 숫자로 리턴하는 메소드
// 일요일(0), 월요일(1), 화요일(2), 수요일(3), 목요일(4), 금요일(5), 토요일(6)
public static int weekday(int year, int month, int day) {
return totalDay(year, month, day)%7;
}
}
-MyCalendar-
public class MyCalendar {
public static void main(String[] args) {
System.out.println(MyCalendarMethod.isLeapYear(2100) ? "윤년" : "평년");
System.out.println(MyCalendarMethod.lastDay(2016, 2));
System.out.println(MyCalendarMethod.totalDay(2017, 10, 14));
System.out.println(MyCalendarMethod.weekday(2017, 10, 14));
}
}
만년달력만들기
-MyCalendar-
import java.util.Scanner;
//달력을 출력하는 클래스
public class MyCalendar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("달력을 출력할 년, 월 : ");
int year = sc.nextInt();
int month = sc.nextInt();
System.out.println("===========================");
System.out.printf(" %4d년 %2d월 \n", year, month);
System.out.println("===========================");
System.out.println("일 월 화 수 금 토");
System.out.println("===========================");
// 1일의 요일 만큼 반복하며 빈칸을 출력한다.
for(int i=1; i<=MyCalendarMethod.weekday(year, month, i); i++) {
System.out.print(" ");
}
// 1일부터 달력을 출력할 달의 마지막 날짜 만큼 반복하며 날짜를 출력한다.
for(int i=1 ; i<=MyCalendarMethod.lastDay(year, month); i++) {
System.out.printf(" %2d " , i);
// 출력한 날짜가 토요일이고 그달의 마지막 날짜가 아니면 줄을 바꾼다.
if(MyCalendarMethod.weekday(year, month, i) == 6 && MyCalendarMethod.lastDay(year, month) != i) {
System.out.println();
}
}
System.out.println("\n===========================");
}
}
댓글남기기