用于计算闰年的Java代码 [英] Java Code for calculating Leap Year

查看:1105
本文介绍了用于计算闰年的Java代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注Java的艺术与科学一书,它展示了如何计算闰年。
本书使用ACM Java Task Force的库。

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.

推荐答案

它们看起来和我一样,但请注意代码中的这一行有一些冗余:

They look the same to me, though note that this line in your code has some redundancy:

else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))

可以替换为:

else if (year % 400 == 0)

如果一个数字是400的倍数,那么它自动也是100和4的倍数。

If a number is a multiple of 400 then it's automatically also a multiple of 100 and 4.

编辑(7年稍后!)

请注意,如果((年%4 == 0)&&年,上述假定存在前面的来自原始问题的%100!= 0)

Please note that the above assumes the presence of the preceding if ((year % 4 == 0) && year % 100 != 0) from the original question!

cletus的答案应该是可接受的答案:https://stackoverflow.com/a/1021373/8331

cletus's answer should be the accepted one: https://stackoverflow.com/a/1021373/8331

(我' d删除我自己的答案,但我不能,因为它是被接受的)

(I'd delete my own answer, but I can't since it's the accepted on)

这篇关于用于计算闰年的Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆