Java 从键盘上输入"year"“month”和“day”,要求通过程序输出 输入的日期为第几年的第几天
1 /** 2 * 编写程序: 3 * 从键盘上输入"year"“month”和“day”,要求通过程序输出 4 * 输入的日期为第几年的第几天 5 * 注:判断一年是否是闰年的标准: 6 * 可以被4整除,但不可被100整除 7 * 或 8 * 可以被400整除 9 * 10 */ 11 12 13 Scanner scan = new Scanner(System.in); 14 System.out.println("请输入年份year:"); 15 int year = scan.nextInt(); 16 System.out.println("请输入"+year+"年的month:"); 17 int month = scan.nextInt(); 18 System.out.println("请输入"+year+"年月份的day:"); 19 int day = scan.nextInt(); 20 21 //定义变量保存总天数 if-else 方法 冗余 22 int sumDays = 0; 23 /* 24 25 if(month == 1) 26 { 27 sumDays = day; 28 } 29 else if(month == 2) 30 { 31 sumDays = 31+ day; 32 } 33 //...... 34 else 35 { 36 //month == 12 37 sumDays = 31+31+....+day; 38 } 39 */ 40 41 //方式二------------------------------------ 42 /* 43 switch(month) 44 { 45 case 1: 46 sumDays = day; 47 break; 48 case 2: 49 sumDays = 31 + day; 50 break; 51 case 3: 52 sumDays = 31+31+day; 53 break; 54 .............. 55 } 56 */ 57 58 //方式三 break在switch-case结构中是可选的。 59 switch(month) 60 { 61 case 12: 62 sumDays += 30; 63 case 11: 64 sumDays += 31; 65 case 10: 66 sumDays += 30; 67 case 9: 68 sumDays += 31; 69 case 8: 70 sumDays += 31; 71 case 7: 72 sumDays += 30; 73 case 6: 74 sumDays += 31; 75 case 5: 76 sumDays += 30; 77 case 4: 78 sumDays += 31; 79 case 3: 80 // sumDays += 28; 81 // 判断year是否是闰年 82 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) 83 { 84 sumDays += 29; 85 } 86 else 87 { 88 sumDays += 28; 89 } 90 91 case 2: 92 sumDays += 31; 93 case 1: 94 sumDays += day; 95 96 } 97 System.out.println("这是"+year+"年"+ month +"月" + day +"日是当年的第" + sumDays + "天"); 98
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15196053.html