본문 바로가기

PROGRAMMING/예제

[Java] Calendar 클래스를 이용해서 달력 출력하기

Calendar 클래스를 이용해서 달력 출력하기.

Calendar가 가지고 있는 필드를 적절히 이용하면 내가 원하는 달의 달력을 출력할 수 있다.

 

근데 성능은 좋은 건지 모르겠다...

 

<출력결과>

1일이 시작하기 전 까지의 요일에는 *이 출력된다.

 

import java.util.Calendar;
import java.util.Scanner;

public class Example 
{

	public static void main(String[] args) 
	{

		Calendar cal = Calendar.getInstance();
		Scanner scan = new Scanner(System.in);
		
		
		cal.clear();
		
		System.out.println("연");
		int y = scan.nextInt();
		System.out.println("월");
		int m = scan.nextInt();
				
		cal.set(y, m - 1, 1);
		
		int weekday = cal.get(Calendar.DAY_OF_WEEK); // 1일의 요일 구하기
		
		System.out.println("일\t월\t화\t수\t목\t금\t토");
		
		
		for(int i = 1; i < weekday; i++) // 1일 전까지 비어있는 요일에 * 출력
		{
			System.out.print("*\t");
		}
		
		for(int i = 0; i < 31; i++) // 최대 31번 루프
		{
			
			int day = cal.get(Calendar.DAY_OF_MONTH); // Calender instance의 현재 날짜
			
			if(i > 1 && day == 1) // day에 1씩 더하기 하다가 새로운 1일이 시작되면 끝내기
			{
				break;
			}
			
			System.out.print(day + "\t"); // 날짜 출력하기
						
			cal.add(Calendar.DAY_OF_MONTH, 1); // 1일 더하기
			
			if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) // 새 날짜의 요일이 일요일이면
			{
				System.out.println(); // 줄바꿈하기
			}
			
		}
	}

}