1.
编写程序,要求用户从键盘输入一个年份和月份,然后显示这个月的天数。例如,如果用户输入的是2012年2月
,那么程序应该显示“2012年2月有29天”。如果用户输入的是2015年3月,那么程序应该显示“2015年3月有31天”。
2.
键盘输入年份和月份
![](https://img-blog.csdnimg.cn/20200921001141415.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpdXdlbnFpbmcxMQ==,size_16,color_FFFFFF,t_70)
3.
判断一下月份是不是1到12个月
![](https://img-blog.csdnimg.cn/20200921001232450.png)
4.0
显示天数 1 月 3 5 7 8 10 12 为31天 4 6 9 11 为30天 2月在闰年时为29天在平常年为28天
闰年 1公历闰年能被4整除且不能被100整除的为闰年,平均每四年中会有一个闰年,世纪年能被400整除的则是闰年
5.全部代码:
package booksTest;
import java.util.Scanner;
public class p53_3_7 {
public static void main(String[] args) {
/*
题目要求
编写程序,要求用户从键盘输入一个年份和月份,然后显示这个月的天数。例如,如果用户输入的是2012年2月
,那么程序应该显示“2012年2月有29天”。如果用户输入的是2015年3月,那么程序应该显示“2015年3月有31天”。
*/
//键盘输入年份和月份
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份");
int Year = sc.nextInt();
System.out.println("请输入月份");
int month = sc.nextInt();
//判断一下月份是不是1到12个月
if (month > 12 || month < 1) {
System.out.println("您输入的月份有误");
} else {
//显示天数 1 月 3 5 7 8 10 12 为31天 4 6 9 11 为30天 2月在闰年时为29天在平常年为28天
//闰年 1公历闰年能被4整除且不能被100整除的为闰年,平均每四年中会有一个闰年,世纪年能被400整除的则是闰年
int Days = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
Days = 31;
System.out.println(Year + "年" + month + "月" + Days + "天");
break;
case 4:
case 6:
case 9:
case 11:
Days = 30;
System.out.println(Year + "年" + month + "月" + Days + "天");
case 2:
if ((Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0)) {
Days = 29;
System.out.println(Year + "年" + month + "月" + Days + "天");
} else {
Days = 28;
System.out.println(Year + "年" + month + "月" + Days + "天");
}
}
}
}
}