Java Code for calculating Leap Year

前端 未结 20 2659
执念已碎
执念已碎 2020-11-22 16:30

I am following \"The Art and Science of Java\" book and it shows how to calculate a leap year. The book uses ACM Java Task Force\'s library.

Here is the code the boo

20条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 17:20

    The correct implementation is:

    public static boolean isLeapYear(int year) {
      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.YEAR, year);
      return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
    }
    

    But if you are going to reinvent this wheel then:

    public static boolean isLeapYear(int year) {
      if (year % 4 != 0) {
        return false;
      } else if (year % 400 == 0) {
        return true;
      } else if (year % 100 == 0) {
        return false;
      } else {
        return true;
      }
    }
    

提交回复
热议问题