public class Test {
public static void main(String[] args) {
// 1)从键盘上输入一个日期
Scanner sc = new Scanner(System.in);
System.out.println("请按照输入年(例如1997):");
int year = sc.nextInt();
System.out.println("请按照输入月(例如1,2……,12):");
int month = sc.nextInt();
System.out.println("请按照输入日(例如1,2,……,31):");
int day = sc.nextInt();
// 2)计算日期的对应的天数
int sumdays = getSumDays(year, month, day);
// 3)打印结果
System.out.println(year + "年" + month + "月" + day + "日,它是" + year + "年" + sumdays + "天");
}
private static int getSumDays(int year, int month, int day) {
int sum = 0;
for (int i = 1; i < month; i++) {
sum += getMonthDays(year, i);
}
sum += day;
return sum;
}
private static int getMonthDays(int year, int month) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
// 如果是闰年返回29,如果不是闰年返回28
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return 29;
} else {
return 28;
}
}
return 0;
}
}
通过给出的日期计算出该日期是这一年的第多少天?
最新推荐文章于 2022-12-17 00:14:23 发布