利用分支结构,计算出某年的某一个月有多少天
源代码:
package day04;
public class Demo02 {
public static void main(String[] args) {
int year = 2000;
int month = 2;
int day = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day=31;
case 4:
case 6:
case 9:
case 11:
day=30;
break;
case 2:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
day=29;
} else {
day=28;
}
}
//利用分支结构,计算出x年x月有多少天
System.out.println(year+"年"+month+"月有"+day+"天");
}
}
优化后的代码:
(优化后使用三元目表达式判断闰年)
package day04;
public class Demo02 {
public static void main(String[] args) {
int year = 2000;
int month = 2;
int day = 0;
switch (month) {
case 2:
day = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 29:28;//优化后使用三元目表达式判断闰年
break;
case 4:
case 6:
case 9:
case 11:
day=30;
default:
day=31;
break;
}
//利用分支结构,计算出x年x月有多少天
System.out.println(year+"年"+month+"月有"+day+"天");
}
}
运行结果: