Java实现闰年判断并计算距离下一个闰年剩余年数问题
Java 闰年判断功能扩展实现
需求说明
在原有判断输入年份是否为闰年的基础上新增逻辑:若输入年份不是闰年,输出距离下一个闰年的剩余年数。
实现逻辑
- 将闰年判断逻辑封装为可复用的
isLeapYear方法,闰年判断规则为能被4整除但不能被100整除,或者能被400整除 - 若输入年份判定为闰年,直接输出对应提示
- 若输入年份不是闰年,从当前年份+1开始逐年校验是否为闰年,直到找到第一个符合规则的年份,计算两个年份的差值即为剩余年数
完整可运行代码
import java.util.Scanner; public class LeapYearTest { // 闰年判断方法 public static boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入年份:"); int year = sc.nextInt(); sc.close(); if (isLeapYear(year)) { System.out.println(year + " 是闰年"); } else { int nextLeapYear = year + 1; while (!isLeapYear(nextLeapYear)) { nextLeapYear++; } int remainYears = nextLeapYear - year; System.out.println(year + " 不是闰年,距离下一个闰年还有 " + remainYears + " 年"); } } }
运行效果示例
输入:2023 → 输出:2023 不是闰年,距离下一个闰年还有 1 年
输入:2024 → 输出:2024 是闰年
输入:1900 → 输出:1900 不是闰年,距离下一个闰年还有 8 年
内容的提问来源于stack exchange,提问作者zaid ragie
相关产品推荐
相关产品推荐

