Java 怎么用switch判断月份天数
在 java 中,可以使用 switch 语句根据传入的月份整数返回对应的天数。具体做法是定义一个方法接收 month 和 year 参数,利用 switch 匹配 1、3、5、7、8、10、12 月返回 31 天,4、6、9、11 月返回 30 天,2 月则通过判断闰年返回 29 或 28 天。这种方法逻辑清晰,能准确处理平年和闰年的差异。

如何优化 switch 结构并处理边界情况
为了优化代码结构,可以将月份分组以减少 case 分支数量,同时确保对非法月份输入进行处理。实际结果中,对于非 1-12 的输入,应返回错误或默认值。通过这种方式,可以避免潜在的逻辑错误,提高代码的可读性和健壮性。

使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
public class MonthDays {
public static int getDaysInMonth(int month, int year) {
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
return 31;
case 4: case 6: case 9: case 11:
return 30;
case 2:
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
return isLeap ? 29 : 28;
default:
throw new IllegalArgumentException("Invalid month: " + month);
}
}
public static void main(String[] args) {
System.out.println(getDaysInMonth(2, 2020)); // 29
System.out.println(getDaysInMonth(2, 2021)); // 28
System.out.println(getDaysInMonth(4, 2021)); // 30
}
}
基于程序中某个输入、条件或结果的具体问题
当输入为 2 月且年份为闰年时,程序会正确返回 29 天;若年份为平年,则返回 28 天。这一行为依赖于闰年判断逻辑:能被 4 整除但不能被 100 整除,或者能被 400 整除的年份为闰年。例如,2020 年是闰年,因此 2 月有 29 天;而 2021 年不是闰年,2 月只有 28 天。
立即学习“Java免费学习笔记(深入)”;

















