java 给出年份 月份 计算并且输出该月的天数 用if else switch 语句编写
时间: 2024-09-19 20:04:17 浏览: 54
在 Java 中,你可以使用 if...else 和 switch 语句结合闰年规则来计算给定月份的天数。下面是一个简单的示例,它会接收输入的年份和月份,然后返回相应的天数:
```java
import java.util.Scanner;
public class MonthlyDays {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入年份:");
int year = input.nextInt();
System.out.println("请输入月份(1-12):");
int month = input.nextInt();
// 判断是否为闰年
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
// 使用 switch 语句确定每个月的天数
int days;
switch (month) {
case 1: // January
case 3: // March
case 5: // May
case 7: // July
case 8: // August
case 10: // October
case 12: // December
days = 31;
break;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
days = 30;
break;
case 2: // February (accounting for leap years)
if (isLeapYear) {
days = 29;
} else {
days = 28;
}
break;
default:
System.out.println("非法月份!请输入1-12之间的数字。");
return;
}
System.out.printf("在%d年%1$02d月,有%2$d天。\n", year, month, days);
}
}
```
阅读全文