Java Code for calculating Leap Year

前端 未结 20 2271
执念已碎
执念已碎 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

    As wikipedia states algorithm for the leap year should be

    (((year%4 == 0) && (year%100 !=0)) || (year%400==0))  
    

    Here is a sample program how to check for leap year.

    0 讨论(0)
  • 2020-11-22 17:21

    It's almost always wrong to have repetition in software. In any engineering discipline, form should follow function, and you have three branches for something which has two possible paths - it's either a leap year or not.

    The mechanism which has the test on one line doesn't have that issue, but generally it would be better to separate the test into a function which takes an int representing a year and returns a boolean representing whether or not the year is a leap year. That way you can do something with it other that print to standard output on the console, and can more easily test it.

    In code which is known to exceed its performance budget, it's usual to arrange the tests so that they are not redundant and perform the tests in an order which returns early. The wikipedia example does this - for most years you have to calculate modulo 400,100 and 4, but for a few you only need modulo 400 or 400 and 100. This is a small optimisation in terms of performance ( at best, only one in a hundred inputs are effected ), but it also means the code has less repetition, and there's less for the programmer to type in.

    0 讨论(0)
提交回复
热议问题