java闰年怎么算,用于计算闰年的Java代码

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))

could be replaced by:

else if (year % 400 == 0)

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

edit: (7 years later!)

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值