天天看點

Java實作 藍橋杯VIP 算法提高 5-3月曆

算法提高 5-3月曆

時間限制:1.0s 記憶體限制:256.0MB

問題描述

  已知2007年1月1日為星期一。設計一函數按照下述格式列印2007年以後(含)某年某月的月曆,2007年以前的拒絕列印。為完成此函數,設計必要的輔助函數也是必要的。

樣例輸入

一個滿足題目要求的輸入範例。

例:

2050 3

樣例輸出

與上面的樣例輸入對應的輸出。

例:

Java實作 藍橋杯VIP 算法提高 5-3月曆

資料規模和約定

  輸入資料中每一個數的範圍。

  例:年 2007-3000,月:1-12。

import java.util.Scanner;


public class 月曆 {
	public static boolean isLeap(int year) {
		boolean flag = false;
		if(year % 4 == 0 && year % 100 != 0)
			flag = true;
		else if(year % 400 == 0)
			flag = true;
		else
			flag = false;
		return flag;
	}
	public static int getDay(int month, int year) {
		int day = 0;
		if (month == 2) {
			if (isLeap(year)) 
				day = 29;
			else 
				day = 28;
		} else if (month < 8) {
			if(month % 2 == 0)
				day = 30;
			else
				day = 31;
		} else {
			if(month % 2 == 0)
				day = 31;
			else
				day = 30;
		}
		return day;
	}
	public static int getFirst(int month, int year) {
		int first = 0;
		int distance = year - 2007;
		int day = 0;
		
		while (distance / 4 >= 1) {
			day += (365 * 4 + 1);
			distance -= 4;
		}
		int count = 0;
		while (distance > 0) {
			if (count == 1) 
				day += 366;
			else
				day += 365;
			count++;
			distance--;
		}
		int fre = 0;
		if(isLeap(year))
			fre = 31 + 29;
		else
			fre = 31 + 28;
		int mon[] = {0, 0, 31, fre, fre+31, fre+61, fre+92, fre+122, fre+153, fre+184, fre+214, fre+245, fre+275};
		day += mon[month];
		first = day % 7;
		return first+1;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int year = sc.nextInt();
		int month = sc.nextInt();
		sc.close();
		
		if(year < 2007)
			return;
		
		int day = getDay(month, year);
		int firstDay = getFirst(month, year);
		
		if(month < 10)
			System.out.println("Calendar " + year + " - 0" + month);
		else
			System.out.println("Calendar " + year + " - " + month);
		for (int i = 0; i < 21; i++) 
			System.out.print("-");
		System.out.print("\n");
		System.out.println("Su Mo Tu We Th Fr Sa ");		
		for (int i = 0; i < 21; i++) 
			System.out.print("-");
		System.out.print("\n");
		int count = 0;
		if(firstDay != 7)
			for (int i = 0; i < firstDay; i++) {
				System.out.print("   ");
				count++;
			}				
		for (int i = 1; i <= day; i++) {
			if(i < 10)
				System.out.print(" " + i + " ");
			else
				System.out.print(i + " ");
			count++;
			if(count % 7 == 0)
				System.out.print("\n");
		}
		System.out.print("\n");
		for (int i = 0; i < 21; i++) 
			System.out.print("-");
	}

}