主方法代码:
1 public static void main(String[] args) { 2 Scanner in = new Scanner(System.in); 3 //输入年份 4 System.out.println("请输入年份(1900之后的):"); 5 int year = in.nextInt(); 6 //输入月份 7 System.out.println("请输入月份:"); 8 int month = in.nextInt(); 9 //判断数据输入是否有误 10 if (year < 1900 || month >12 || month < 1){ 11 System.out.println("对不起,你输入的数据有误!"); 12 return; 13 } 14 //获取1900年到输入年份的总天数 15 int allDayOfYear = getAllDayOfYear(1900,year); 16 17 //获取输入年份从1月到输入月份的总天数 18 int allDayOfMonth = getAllDayOfMonth(year,1,month); 19 20 //获得总天数 21 int allDay = allDayOfYear + allDayOfMonth; 22 //打印日期 23 printCalendar(allDay,getDayOfMonth(year,month)); 24 25 }
计算1900到输入年份的总天数的方法代码
public static int getAllDayOfYear(int startYear,int endYear){ //定义年的总天数 int allDayOfYear = 0; for (int i = startYear; i < endYear; i++) { if (judgeLeapYear(i)){ allDayOfYear += 366; }else { allDayOfYear +=365; } } return allDayOfYear; }
计算输入年份从1月到输入月份的总天数方法代码
1 public static int getAllDayOfMonth(int year,int startMonth,int endMonth){ 2 int allDayOfMonth = 0; 3 for (int i = startMonth; i < endMonth; i++) { 4 allDayOfMonth += getDayOfMonth(year,i); 5 } 6 return allDayOfMonth; 7 }
获得每一个月的天数方法代码
1 public static int getDayOfMonth(int year,int month){ 2 //定义月的天数 3 int day = 0; 4 switch (month){ 5 case 1: 6 case 3: 7 case 5: 8 case 7: 9 case 8: 10 case 10: 11 case 12: 12 day = 31; 13 break; 14 case 4: 15 case 6: 16 case 9: 17 case 11: 18 day = 30; 19 break; 20 case 2: 21 if (judgeLeapYear(year)){ 22 day = 29; 23 }else { 24 day = 28; 25 } 26 break; 27 } 28 return day; 29 }
判断是否为闰年方法代码
1 public static boolean judgeLeapYear(int year){ 2 if (year % 4 == 0 && year % 100 !=0 || year % 400 == 0){ 3 return true; 4 } 5 return false; 6 }
打印日历方法代码
1 public static void printCalendar(int allDay,int day){ 2 //打印开头的信息 3 System.out.println("星期日 星期一 星期二 星期三 星期四 星期五 星期六"); 4 //换行变量 5 int num = 0; 6 //计算输入的月份1号是星期几 7 int week = allDay % 7 +1; 8 for (int i = 0; i < week; i++) { 9 System.out.print(" "); 10 num++; 11 } 12 //打印日期 13 for (int i = 1; i <= day; i++) { 14 //判断 15 if (num %7 == 0){ 16 System.out.println(); 17 } 18 System.out.print(i+" "); 19 num++; 20 } 21 }