Java判断闰年算法详解及代码示例
一、闰年判断核心逻辑
闰年判断需满足以下任一条件:
普通闰年:能被4整除但不能被100整除(如2004年)
世纪闰年:能被400整除(如2000年)
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
二、完整代码实现与解析
1. 基础判断类
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(" 请输入年份:");
int year = scanner.nextInt;
if (isLeapYear(year)) {
System.out.println(year + " 是闰年");
} else {
System.out.println(year + " 不是闰年");
}
}
private static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
```
### 2. 扩展功能实现
- **批量判断**:支持输入多个年份进行连续判断
- **异常处理**:增加非数字输入的容错机制
```java
public static void batchCheck {
while (true) {
try {
System.out.print(" 请输入年份(输入Q退出):");
String input = scanner.next;
if ("Q".equalsIgnoreCase(input)) break;
int year = Integer.parseInt(input);
System.out.println(year + ":" + (isLeapYear(year) ? "闰年" : "平年"));
} catch (NumberFormatException e) {
System.out.println(" 请输入有效数字!");
}
}
}
```
---
## 三、代码优化技巧
1. **运算优先级优化**:通过括号明确运算顺序,避免歧义
2. **边界值测试**:
- 1900年(非闰年)
- 2000年(闰年)
- 2024年(闰年)
3. **性能提升**:对于频繁调用场景,可缓存计算结果
---
## 四、常见问题解答
### Q1:如何处理非数字输入?
``````java
try {
int year = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println(" 输入无效,请重新输入!");
}
```
### Q2:为什么1900年不是闰年?
- 虽然能被4整除,但作为整百年份需满足能被400整除的额外条件
### Q3:如何批量验证多个年份?
- 使用循环结构配合异常处理机制实现连续输入判断
---
## 五、SEO优化要点
1. **标题优化**:包含核心关键词"Java判断闰年",控制在28字以内
2. **内容结构**:
- 使用`<h2>`划分章节
- 关键代码段使用`<pre>`标签
- 重要术语加粗标注
3. **关键词布局**:
- 标题:1次
- 正文:自然融入3-5次
- 元描述:包含关键词
> 本文通过清晰的算法解析、完整的代码演示及SEO优化实践,帮助开发者快速掌握Java闰年判断方法,同时满足搜索引擎收录要求。