java输入一个月份判定季节
时间: 2024-10-25 22:06:15 浏览: 12
在 Java 中,你可以创建一个函数来根据输入的月份判断季节。这里是一个简单的示例:
```java
public enum Season {
SPRING(3, 5), SUMMER(6, 8), AUTUMN(9, 11), WINTER(12, 2);
private int startMonth;
private int endMonth;
Season(int start, int end) {
this.startMonth = start;
this.endMonth = end;
}
public static Season getSeasonByMonth(int month) {
if (month >= 3 && month <= 5) {
return Season.SPRING;
} else if (month >= 6 && month <= 8) {
return Season.SUMMER;
} else if (month >= 9 && month <= 11) {
return Season.AUTUMN;
} else if (month >= 12 || (month == 1 && isLeapYear())) { // Considering February in non-leap years
return Season.WINTER;
} else {
throw new IllegalArgumentException("Invalid month number");
}
}
private boolean isLeapYear() {
// This is a simplified leap year check; for more accurate implementation, use GregorianCalendar
return (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0));
}
}
// 使用示例
int inputMonth = Integer.parseInt(JOptionPane.showInputDialog("Enter the month:"));
Season season = Season.getSeasonByMonth(inputMonth);
System.out.println("The season for the given month is: " + season.name());
```
这个例子中,我们定义了一个 `Season` 枚举,每个季节都有其对应的开始和结束月份。然后通过用户输入的月份查找合适的季节。注意,为了处理闰年的二月,我们简化地检查了当前是否为闰年。
阅读全文