编程实现输出某年某个月的天数。使用switch。java
时间: 2024-10-12 15:17:11 浏览: 26
java 输入某年某月某日,判断这一天是这一年的第几天
在Java中,你可以使用`switch`结构结合嵌套的`if`条件来计算给定年月的天数。这里是一个简单的示例,它假设月份从1到12,并考虑了闰年的规则:
```java
public int getDaysInMonth(int year, int month) {
int days;
switch (month) {
case 2: // February
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { // Leap year check
days = 29;
} else {
days = 28;
}
break;
case 4:
case 6:
case 9:
case 11: // Months with 30 days
days = 30;
break;
default: // January, March, May, July, August, October, December
days = 31;
break;
}
return days;
}
// 使用示例
int year = 2023; // 输入年份
int month = 2; // 输入月份
System.out.println("Number of days in " + year + " " + month + " is: " + getDaysInMonth(year, month));
阅读全文