java例题_14 该日期一年中的第几天问题

 1 /*14 【程序 14 求日期】 
 2 题目:输入某年某月某日,判断这一天是这一年的第几天? 
 3 程序分析:以 3 月 5 日为例,应该先把前两个月的加起来,然后再加上 5 天即本年的第几天,特殊情况,闰年且输入月份大于 3 时需考虑多加一天。 
 4 */
 5 
 6 /*分析:
 7  * 1、得到键盘上的数字,并以“.”间隔,分别将年月日存入year,month,day中
 8  * 2、判断月份是几月,如果一月就直接访问日,如果2月就day+31,如果大于等于三月且小于等于8月,则31*month/2+30*(month-month/2)-3+day,
 9  *    如果大于8月,则31*(month+1)/2+30*(month-(month+1)/2)-3+day
10  * 3、判断是否为闰年,如果是,再加1----闰年:四年一闰,百年不闰,四百年再闰
11  * */
12 
13 
14 package homework;
15 
16 import java.util.Scanner;
17 
18 public class _14 {
19 
20     public static void main(String[] args) {
21         // 声明t,表示在哪儿一天
22         int t=0;
23         //从键盘得到年月日
24         Scanner sc=new Scanner(System.in);
25         System.out.println("请输入年月日,并以空格相间(如:2020 01 01):");
26         int year=sc.nextInt();
27         int month=sc.nextInt();
28         int day=sc.nextInt();
29 //        System.out.println(year+"年"+month+"月"+day+"日"); //测试
30         
31         if (month==1) {
32             t=day;
33         }
34         else if (month==2) {
35             t=day+31;
36         }
37         else if ((month>=3)&(month<=8)) {
38             t=31*month/2+30*(month-month/2-1)-2+day;
39 //            System.out.println("大月:"+(month+1)/2+"  小月:"+(month-(month+1)/2-1)+"  天数:"+day);
40 //            System.out.println("大月天数:"+31*(month)/2+"   小月天数:"+(30*(month-(month+1)/2-1)-2));
41         }
42         else if (month<=12) {
43             t=31*(month)/2+30*(month-(month+1)/2-1)-2+day;
44 //            System.out.println("大月:"+(month)/2+"  小月:"+(month-(month+1)/2-1)+"  天数:"+day);
45 //            System.out.println("大月天数:"+31*(month)/2+"   小月天数:"+(30*(month-(month+1)/2-1)-2));
46         }
47         else {
48             //保证月份正确-----暂时还不会异常捕获
49         }
50 //        System.out.println(year+"年"+month+"月"+day+"日是这一年中的第"+t+"天");
51         //判断是否为闰年
52         if(((year%4==0)&(year%100!=0))||(year%400==0)){
53             t=t+1;
54         }
55         //还有判定月份,日期等是否合法,目前只能用if实现,不会异常捕获,暂时不写了
56         System.out.println(year+"年"+month+"月"+day+"日是这一年中的第"+t+"天");
57         
58     }
59 
60 }

 

posted @ 2020-02-12 22:25  浪漫主义程序员  阅读(501)  评论(0编辑  收藏  举报