任务概述
计算该年该月天数 一年中有 12 个月,而每个月的天数是不一样的。
- 其中大月 31 天,分别为 1,3,5,7,8,10,12 月,小月 30 天,分别 为 4,6,9,11 月。
- 还有二月比较特殊,平 年的二月只有 28 天,
- 而闰年的二月有 29 天,由用户在控制台输入年份和月份, 程序计算该年该月的天数
代码实现
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("请输入你查询的年份");
int year =sc.nextInt();
System.out.println("请输入你查询的月份");
int month=sc.nextInt();
int day;
if(year%4==0&&year%100!=0||year%400==0) {//判断是否为闰年
day=29;//平 年的二月只有 29 天,
}else {
day=28;//润年的二月只有 28 天,
}
switch(month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println(year+"年"+month+"月有31天");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println(year+"年"+month+"月有30天");
break;
case 2:
System.out.println(year+"年"+month+"月有"+day+"天");
}
}
}
运行结果
请输入你查询的年份:
2021
请输入你查询的月份:
8
你查询的为:2021年8月有31天