我关注“Java的艺术与科学”一书,它展示了如何计算闰年。本书使用ACM Java任务组的库。用于计算闰年的Java代码
这里是书籍使用代码:
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.");
}
}
现在,这是我如何计算闰年。
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.");
}
}
}
我的代码有什么问题吗?或者我应该使用本书提供的代码吗?
编辑::上述两个代码工作正常,我想问的是哪个代码是计算闰年的最佳方式。
最好的代码将使用受信任的库,而不是。 Cletus使用Calendar类的建议是一个很好的例子。 – 2009-06-20 12:52:30
如果使用常规Java库,你是正确的。但在我的课程中,我正在使用ACM的Java Task Force的库。 http://www-cs-faculty.stanford.edu/~eroberts/jtf/ – 2009-06-20 13:06:32
这里是类似的线程。 http://stackoverflow.com/questions/7395699/calculate-leap-year-in-java/7395759#7395759 – CharithJ 2011-09-13 01:41:20