java实现万年历

package com.donmo.work;

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

/**
 *@author donmo
 *@date 2020年7月7日
 *@Description 万年历
 */

public class WanYearDate {

	public static void main(String[] args) {
		
		System.out.print("请输入你要查找的年份:");
		Scanner scanner = new Scanner(System.in);
		int year = scanner.nextInt();
		System.out.print("请输入你要查找的月份:");
		int month = scanner.nextInt();
		print(year, month, dayCount(year, month));
	}
	
	
	/**
	 * 判断是否为闰年   
	 * 小技巧:直接取年份得后两位数,对4取余,为零就是闰年
	 */
	private static boolean isLeapYear(int year) {
		if(year%100==0) {
			if(year%400==0) {
				return true;
			}
		}else {
			if(year%4==0) {
				return true;
			}
		}
		return false;
	}
	
	//月得天数
	private static int dayCount(int year,int month) {
		int num = 0;
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			num = 31;
			break;
			
		case 4:
		case 6:
		case 9:
		case 11:
			num = 30;
			break;
		case 2:
			if(isLeapYear(year)) {
				num = 29;
			}else {
				num = 28;
			}
			break;
		}
		return num;
	}
	
	//打印
	private static void print(int year,int month,int num) {
		System.out.println("=============================="+year+"年-"+month+"月"+"============================");
		System.out.println();
		System.out.println("\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t星期日");
		
		//这个月的第一天是星期几
		int dayOfWeek = dayOfWeek(year, month);
		
		dayOfWeek = dayOfWeek==0?7:dayOfWeek;
		
		for(int i =0;i<dayOfWeek-1;i++) {
			System.out.print("\t");
		}
		for(int i =1;i<num+1;i++) {
			System.out.print("\t"+i);
			
			if(dayOfWeek==7) {
				dayOfWeek=0;
				System.out.println();
			}
			dayOfWeek++;
		}
		
		
		System.out.println();
		System.out.println("===================================================================");
		
	}
	
	//返回当前月第一天是星期几
	private static int dayOfWeek(int year,int month) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month-1,1);
		return calendar.get(calendar.DAY_OF_WEEK)-1;
	}
}

效果图:java实现万年历_第1张图片

你可能感兴趣的:(java实现万年历)