计算闰年的Java代码 [英] Java Code for calculating Leap Year
本文介绍了计算闰年的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.
这是书中使用的代码:
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.
推荐答案
正确的实现是:
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;
}
}
这篇关于计算闰年的Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文