import java.time.DayOfWeek;
import java.util.Scanner;
/**
* 使用方法打印日历
*
* @param args
*/
public class PrintCalender {
/** 对应年份和月份 **/
private static int year = Integer.MIN_VALUE;
private static int month = Integer.MIN_VALUE;
/** 对应每个月份的天数 **/
private static int[] dayOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintCalender();
}
private static void PrintCalender() {
// 让用户输入年月
InputYearAndMonth();
// 计算用户输入的年月份的天数(计算各年的总天数,各月的总天数)
int sum = getSumDayOfYears();
sum += getSumDayOfMonth();
sum ++;
// 打印年份和月份
// 打印月份的标题
PrintMonthTitle();
// 根据某月是星期几,打印日历的内容
PrintCalendarContent(sum % 7);
}
/**
* 根据当月1号的周几打印日历的内容
*/
private static void PrintCalendarContent(int dayOfWeek) {
int sepCount = 0;
if (dayOfWeek == 0) {
sepCount = 6;
} else {
sepCount = dayOfWeek - 1;
}
for (int i = 0; i < sepCount; i++) {
System.out.print("\t");
}
for (int i = 0; i < dayOfMonth[month - 1]; i++) {
System.out.print(i + 1);
if ((dayOfWeek + i) % 7 == 0) {
System.out.print("\n");
} else
System.out.print("\t");
}
}
/**
* 打印年份和月份和打印月份的标题
*/
private static void PrintMonthTitle() {
String[] monthName = { "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" };
System.out.print("\t\t" + year + "\t" + monthName[month - 1] + "\n");
String[] weekDays = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天" };
for (int i = 0; i < weekDays.length; i++) {
System.out.print(weekDays[i] + "\t");
}
System.out.println();
}
/**
* 获得1900-year年的总天数
*/
private static int getSumDayOfYears() {
// 需要判断用户是否已经输入年份
if (year == Integer.MIN_VALUE) {
System.out.print("年份错误,请重新输入年份");
InputYearAndMonth();
}
int sum = 0;
for (int i = 1900; i <= year; i++) {
if (isLeapYear(year))
sum += 366;
else
sum += 365;// 每一年累加365天
}
return sum;
}
/**
* 得到year年1月1号year年month-1月最后一天的总天数
*/
private static int getSumDayOfMonth() {
int sum = 0;
int[] dayOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for (int i = 0; i < month - 1; i++) {
sum += dayOfMonth[i];
}
// year为闰年,2月为29,天数+1
if (isLeapYear(year) && month >= 3) {
sum++;
}
return sum;
}
/**
* 用来判断年份是不是闰年
*
* @return
*/
private static boolean isLeapYear(int year) {
return year % 400 == 0 || year % 4 == 0 && year % 100 != 0;
}
/**
* 接收用户输入的年份和月份
*/
private static void InputYearAndMonth() {
Scanner input = new Scanner(System.in);
System.out.print("请输入年份:");
year = input.nextInt();
System.out.print("请输入月份: ");
month = input.nextInt();
input.close();
input = null;
}
}