Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Code for calculating Leap Year

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 books uses:

import acm.program.*;  public class LeapYear extends ConsoleProgram {     public void run()     {          println("This program calculates leap year.");         int year = readInt("Enter the year: ");               boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));          if (isLeapYear)         {             println(year + " is a leap year.");         } else             println(year + " is not a leap year.");     }  } 

Now, this is how I calculated the leap year.

import acm.program.*;  public class LeapYear extends ConsoleProgram {     public void run()     {          println("This program calculates leap year.");         int year = readInt("Enter the year: ");          if ((year % 4 == 0) && year % 100 != 0)         {             println(year + " is a leap year.");         }         else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))         {             println(year + " is a leap year.");         }         else         {             println(year + " is not a leap year.");         }     } } 

Is there anything wrong with my code or should i use the one provided by the book ?

EDIT :: Both of the above code works fine, What i want to ask is which code is the best way to calculate the leap year.

like image 656
Ibn Saeed Avatar asked Jun 20 '09 09:06

Ibn Saeed


2 Answers

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;   } } 
like image 154
cletus Avatar answered Sep 22 '22 14:09

cletus


java.time.Year::isLeap

I'd like to add the new java.time way of doing this with the Year class and isLeap method:

java.time.Year.of(year).isLeap(); 
like image 32
bowmore Avatar answered Sep 20 '22 14:09

bowmore