题目:输入某年某月某日,判断这一天是这一年的第几天?
分析:闰年二月29,普通年份28
1月31;2月 ,3月31;4月30;5月31;6月30;7月31;
8月31;9月30;10月31;11月30;12月31
代码:
1 import java.util.Scanner;
2
3 public static void main(String[] args) {
4 Scanner s = new Scanner(System.in);
5 int year, month, day;
6 do {
7 System.out.println("输入年份:");
8 year = s.nextInt();
9 if (year < 1) {
10 System.out.println("请输入正确年份");
11 continue;
12 } else
13 break;
14 } while (true);
15 do {
16 System.out.println("输入月份:");
17 month = s.nextInt();
18 if (month < 1 || month > 12) {
19 System.out.println("请输入正确月份");
20 continue;
21 } else
22 break;
23 } while (true);
24 do {
25 System.out.println("输入日:");
26 day = s.nextInt();
27 if (isDays(year, month, day))
28 break;
29 } while (true);
30 //已经输入正确是年月日,进行判断并累加天数
31 int sum = day;//本月日期
32 //从12月倒叙进行穿透累加
33 switch (month - 1) {//-1为减除本月日期
34 case 11:
35 sum += 30;
36 case 10:
37 sum += 31;
38 case 9:
39 sum += 30;
40 case 8:
41 sum += 31;
42 case 7:
43 sum += 31;
44 case 6:
45 sum += 30;
46 case 5:
47 sum += 31;
48 case 4:
49 sum += 30;
50 case 3:
51 sum += 31;
52 case 2:
53 if (year % 4 == 0) {
54 sum += 29;
55 } else {
56 sum += 28;
57 }
58 case 1:
59 sum += 31;
60 }
61 System.out.println("这是今年的第" + sum + "天");
62 }
63
64 //判断日期是否正确
65 public static boolean isDays(int year, int month, int day) {
66 if (day < 1 || day > 31) {
67 System.out.println("日期不正确,请从1~31中选取");
68 return false;
69 }
70 int a = 2;//闰年(29)平年(28)不同
71 int[] b = {1, 3, 5, 7, 8, 10, 12};//31天上限的月份
72 int[] c = {4, 6, 9, 11};//30天上线的月份
73 if(month==2){
74 if (year%4==0){
75 if(day>29){
76 System.out.println("闰年只有29天");
77 return false;
78 }return true;
79 }else {
80 if(day>28){
81 System.out.println("平年只有28天");
82 return false;
83 }return true;
84 }
85 }else if (findMonth(b,month)){
86 if (day > 31) {
87 System.out.println("这个月只有31天");
88 return false;
89 } else {
90 return true;
91 }
92 }else {
93 if (day > 30) {
94 System.out.println("这个月只有30天");
95 return false;
96 } else {
97 return true;
98 }
99 }
100 }
101 //查找元素是否在数组中
102 public static boolean findMonth(int[]b,int month){
103 for (int i : b) {
104 if(month==i)
105 return true;
106 }
107 return false;
108 }