import java.util.Scanner;
public class PerpetualCalendar {
/**
知识点:方法版万年历
*/
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("请输入年:"); //2021
int year = scan.nextInt();
System.out.println("请输入月:"); //7
int month = scan.nextInt();
//1.计算1900~输入年的总天数
int allDayOfYear = getAllDayOfYear(1900,year);
//2.计算1~输入月的总天数
int allDayOfMonth = getAllDayOfMonth(year,1,month);
//3.年的总天数 + 月的总天数
int allDay = allDayOfYear + allDayOfMonth + 1;
//4.获取星期
int week = getWeek(allDay);
//5.获取当月天数
int day = getDay(year,month);
//5.打印日期
printCalendar(year,month,day,week);
}
//打印日期
public static void printCalendar(int year,int month,int day,int week){
System.out.println(" --- " + year + "年 - " + month + "月 ---");
System.out.println("周一\t周二\t周三\t周四\t周五\t周六\t周日");
int num = 0;
for(int i = 1;i<week;i++){
System.out.print("\t");
num++;
}
for(int i = 1;i<=day;i++){
System.out.print(i + "\t");
num++;
if(num%7==0){
System.out.println();
}
}
}
//获取星期
public static int getWeek(int allDay){
if(allDay%7 == 0){
return 7;
}
return allDay%7;
}
//获取开始月到结束月的天数
public static int getAllDayOfMonth(int year,int startMonth,int endMonth){
int allDayOfMonth = 0;
for(int i = startMonth;i<endMonth;i++){
allDayOfMonth += getDay(year,i);
}
return allDayOfMonth;
}
//获取当月天数
public static int getDay(int year,int month){
int day = 0;
switch(month){
case 1:case 3:case 5:case 7:case 8:case 10:case 12:
day=31;
break;
case 4:case 6:case 9:case 11:
day=30;
break;
case 2:
if(isLeapYear(year)){
day=29;
}else{
day=28;
}
break;
}
return day;
}
//获取开始年到结束年的天数
public static int getAllDayOfYear(int startYear,int endYear){
int allDayOfYear = 0;
for(int i = startYear;i<endYear;i++){
if(isLeapYear(i)){
allDayOfYear+=366;
}else{
allDayOfYear+=365;
}
}
return allDayOfYear;
}
//判断是否是闰年
public static boolean isLeapYear(int year){
if(year%4==0&&year%100!=0 || year%400== 0){
return true;
}
return false;
}
}
|