本文实例讲述了JAVA实现的简单万年历。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
import java.util.Scanner; public class PrintCalendar { public static void main(String[] args) { int years = 0 ; int month = 0 ; int days = 0 ; boolean isRun = false ; //從控制台輸入年,月 Scanner input = new Scanner(System.in); System.out.print( "請輸入年份:" ); years = input.nextInt(); System.out.print( "請輸入月份:" ); month = input.nextInt(); System.out.println( "\n*********" +years+ "年" +month+ "月 日曆表************" ); //判断是否是闰年 if ((years % 4 == 0 && years % 100 != 0 ) || (years % 400 == 0 )){ isRun = true ; } int totalDays = 0 ; //累計天數 //計算距離1900年1月1日的天數 for ( int i = 1900 ; i < years; i++){ if ((i % 4 == 0 && i % 100 != 0 ) || (i % 400 == 0 )){ totalDays = totalDays + 366 ; } else { totalDays = totalDays + 365 ; } } int beforeDays = 0 ; //根據月份判斷天數 for ( int j = 1 ; j <= month; j++){ switch (j){ case 1 : case 3 : case 5 : case 7 : case 8 : case 10 : case 12 : days = 31 ; break ; case 4 : case 6 : case 9 : case 11 : days = 30 ; break ; case 2 : if (isRun){ days = 29 ; } else { days = 28 ; } default : System.out.println( "输入月份不正确!!" ); } if (j < month){ beforeDays = beforeDays + days; } } totalDays = totalDays + beforeDays; //統計到目前總天數 int firstDayOfMonth = 0 ; int temp = 1 + totalDays % 7 ; if (temp == 7 ){ firstDayOfMonth = 0 ; //週日 } else { firstDayOfMonth = temp; } /* 输出日历 */ System.out.println( "星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六" ); for ( int k = 0 ; k < firstDayOfMonth; k++){ System.out.print( "\t" ); } for ( int m = 1 ; m <= days; m++){ System.out.print( m + "\t" ); if ((totalDays + m) % 7 == 6 ){ System.out.print( "\n" ); } } } } |
希望本文所述对大家Java程序设计有所帮助。