1.先确定年份,月日从键盘中输入,计算这一天是这一年中的第几天。
/*
从键盘上输入2019年的"mouth" 和 "day",要求通过程序输出输入的日期为2019年的第几天。
*/
import java.util.Scanner;
class SwitchTest3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入2019年n的 mouth ");
int month = sc.nextInt();
System.out.println("请输入2019年的 day ");
int day = sc.nextInt();
// 累加器:输出这一年的多少天
int sumDays = 0;
// 方式一
if (month == 1){
sumDays = day;
}else if (month == 2 ){
sumDays = 31 + day;
}else if (month == 3 ){
sumDays = 31 + 28 + day;
}else if (month == 4 ){
sumDays = 31 + 28 + 31 + day;
}
// 方式二
switch (month){
case 1:
sumDays = day;
break;
case 2:
sumDays = 31 + day;
break;
case 3:
sumDays = 31 + 28 + day;
break;
case 4:
sumDays = 31 + 28 + 31 + day;
break;
case 5:
sumDays = 31 + 28 + 31 + 30 + day;
break;
}
// 方式一和方式二代码冗余度很高,继续用switch语句,但是反向推理
switch (month){
case 12:
sumDays += 30;
case 11:
sumDays += 31;
case 10:
sumDays += 30;
case 9:
sumDays += 31;
case 8:
sumDays += 31;
case 7:
sumDays += 30;
case 6:
sumDays += 31;
case 5:
sumDays += 30;
case 4:
sumDays += 31;
case 3:
sumDays += 28;
case 2:
sumDays += 31;
case 1:
sumDays += day;
}
System.out.println("2019年" + month + "月" + day + "日,是这一年的第" + sumDays + "天");
}
}
2.上述代码没有考虑到闰年和平年的情况。
注意:本质问题: 2 月 是 28天 ,还是29天。
import java.util.Scanner;
class SwitchTest3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入 year ");
int year = sc.nextInt();
System.out.println("请输入2019年n的 mouth ");
int month = sc.nextInt();
System.out.println("请输入2019年的 day ");
int day = sc.nextInt();
// 累加器:输出这一年的多少天
int sumDays = 0;
switch (month){
case 12:
sumDays += 30;
case 11:
sumDays += 31;
case 10:
sumDays += 30;
case 9:
sumDays += 31;
case 8:
sumDays += 31;
case 7:
sumDays += 30;
case 6:
sumDays += 31;
case 5:
sumDays += 30;
case 4:
sumDays += 31;
case 3:
// sumDays += 28;
// 闰年可以被 4 整除,但是不可以被100整除 || 可以被 400 整除
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
// 说明这一年是闰年
sumDays += 29;
}else {
sumDays += 28;
}
case 2:
sumDays += 31;
case 1:
sumDays += day;
}
System.out.println(year + "年" + month + "月" + day + "日,是这一年的第" + sumDays + "天");
}
}
转载出处:https://www.it610.com/article/1359972988442664960.htm