「Java案例」判断是否是闰年的方法
定义方法实现闰年判断与天数计算
闰年判断与天数计算实现
编写一个程序,要求编写方法public static boolean isLeapYear(int year)
实现判断闰年方法;编写方法public static int numberOfDays(int year)
计算一年有多少天。
# 源文件保存为“YearCalculator.java”
public class YearCalculator {public static void main(String[] args) {int testYear = 2024;System.out.println(testYear + "年是闰年吗? " + isLeapYear(testYear));System.out.println(testYear + "年有 " + numberOfDays(testYear) + " 天");}// 判断是否为闰年public static boolean isLeapYear(int year) {if (year % 4 != 0) {return false;} else if (year % 100 != 0) {return true;} else {return year % 400 == 0;}}// 计算一年的天数public static int numberOfDays(int year) {return isLeapYear(year) ? 366 : 365;}
}
运行结果
2024年是闰年吗? true
2024年有 366 天
代码解析:
isLeapYear
方法遵循闰年判断规则:- 不能被4整除的不是闰年
- 能被4整除但不能被100整除的是闰年
- 能被100整除但不能被400整除的不是闰年
- 能被400整除的是闰年
numberOfDays
方法直接利用isLeapYear
的结果返回365或366天
相关案例解析
计算某年某月的天数
编写一个程序,要求编写方法public static boolean isLeapYear(int year)
实现判断闰年方法;编写方法public static int getMonthDays(int year, int month)
计算某年某月的天数。
# 源文件保存为“MonthDays.java”
public class MonthDays {public static void main(String[] args) {int year = 2024;int month = 2;System.out.println(year + "年" + month + "月有 " + getMonthDays(year, month) + " 天");}public static int getMonthDays(int year, int month) {switch (month) {case 1: case 3: case 5: case 7: case 8: case 10: case 12:return 31;