java判断是否为闰年的代码

您所在的位置:网站首页 怎么判断是否为闰年代码 java判断是否为闰年的代码

java判断是否为闰年的代码

2024-07-10 06:08| 来源: 网络整理| 查看: 265

以下是Java代码,用于判断一个年份是否为闰年:

public class LeapYear { public static void main(String[] args) { int year = 2020; // 替换为要判断的年份 boolean isLeapYear = isLeapYear(year); if (isLeapYear) { System.out.println(year + "是闰年"); } else { System.out.println(year + "不是闰年"); } } public static boolean isLeapYear(int year) { if (year % 4 != 0) { return false; // 不是4的倍数,不是闰年 } else if (year % 100 != 0) { return true; // 是4的倍数但不是100的倍数,是闰年 } else if (year % 400 != 0) { return false; // 是100的倍数但不是400的倍数,不是闰年 } else { return true; // 是400的倍数,是闰年 } } }

这段代码定义了一个名为LeapYear的类,其中包含一个main方法和一个isLeapYear方法。main方法中指定了要判断的年份,然后调用isLeapYear方法进行判断,最后根据判断结果输出相应的信息。

isLeapYear方法接受一个整数参数year,表示要判断的年份。它通过一系列的条件判断来确定该年份是否为闰年。如果满足闰年的条件,返回true;否则返回false。

在判断闰年的规则中,如果一个年份能被4整除但不能被100整除,或者能被400整除,那么这个年份就是闰年。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3