首先位java的结构图
然后是第一种代码(第一种完全在主函数中编写):
1 package com.cal;
2 public class MyCalendar01 {
3 public static void main(String[] args) {
4 int year = 2017;
5 //显示某一年的日历
6 System.out.println(year + "年的日历");
7 for (int i = 1; i < 13; i++) {
8 int month = i;
9 //显示某一月的开头
10 System.out.println(year + "年" + month + "月的日历");
11 System.out.println("日 一 二 三 四 五 六");
12
13 int monthDays = 0;
14 //判断此月有多少天
15 switch (month) {
16 case 1:
17 case 3:
18 case 5:
19 case 7:
20 case 8:
21 case 10:
22 case 12:
23 monthDays = 31;
24 break;
25 case 4:
26 case 6:
27 case 9:
28 case 11:
29 monthDays = 30;
30 break;
31 case 2:
32 //判断是否为闰年
33 if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
34 monthDays = 29;
35 } else {
36 monthDays = 28;
37 }
38 break;
39 default:
40 break;
41 }
42 //计算每月为星期几,weekday是某月星期几
43 int weekDay = 0;
44 //计算1900年到该年之间一共有多少天
45 int days = 0;
46 for (int j = 1900; j < year; j++) {
47 int currentYear = j;
48 if (currentYear % 4 == 0 && currentYear % 100 != 0
49 || currentYear % 400 == 0) {
50 days = days + 366;
51 } else {
52 days = days + 365;
53 }
54 }
55 //算出该年某月之前有多少天
56 for (int j = 1; j < month; j++) {
57 int currentmonth = j;
58 switch (currentmonth) {
59 case 1:
60 case 3:
61 case 5:
62 case 7:
63 case 8:
64 case 10:
65 case 12:
66 days = days + 31;
67 break;
68 case 4:
69 case 6:
70 case 9:
71 case 11:
72 days = days + 30;
73 break;
74 case 2:
75 if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
76 days = days + 29;
77 } else {
78 days = days + 28;
79 }
80 break;
81 default:
82 break;
83 }
84 }
85 weekDay = (days % 7 + 1) % 7;
86 //显示某月主题部分
87 for (int j = 0; j < weekDay; j++) {
88 System.out.print(" ");
89