题目描述
编写一个程序实现闰年的判断,以及指定月份的天数。(分别使用if和switch分支语句来实现)
提示:
1.能被400整除的年份,是闰年。
2.能被4整除,并且不能被100整除的年份,是闰年。
输入
2020 2
输出
2020是闰年,该年2份有29天
实现代码如下:
import java.util.Scanner;
public class Test0 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入年月(用空格隔开):");
int year = sc.nextInt();
int month = sc.nextInt();
int day = 31;
// 31 29 31 30 31 30 31 31 30 31 30 31 闰年
// 31 28 31 30 31 30 31 31 30 31 30 31 不是闰年
ifelse(month,year,day);
//switchcase(month, year, day);
}
//自定义ifelse方法实现
private static void ifelse(int month, int year, int day) {
boolean b = year % 400 == 0 || year %4 == 0 && year % 100 != 0;
if(month == 2) {
day = b == true ? 29 : 28;
}else if(month == 4 || month == 6 || month == 9 || month == 11) {
day = 30;
}else {
day = 31;
}
print(month, year, day);
}
//自定义switchcase方法实现
/*private static void switchcase(int month,int year,int day) {
boolean b = year % 400 == 0 || year %4 == 0 && year % 100 != 0;
switch (month) {
case 2:
day = b == true ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
default:
day = 31;
break;
}
print(month, year, day);
}*/
private static void print(int month, int year, int day) {
boolean b = year % 400 == 0 || year %4 == 0 && year % 100 != 0;
System.out.println(year + (b==true?"是闰年,该年":"不是闰年,该年") + month + "份有" + day + "天");
}
}
注:代码仅供参考。