我正在阅读《 Java的艺术与科学》这本书,它展示了如何计算a年。该书使用了ACM Java Task Force的库。
这是这些书使用的代码:
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."); } }
现在,这就是我计算calculated年的方式。
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."); } } }
我的代码有什么问题吗?还是我应该使用本书提供的代码?
编辑::上面的两个代码都工作正常,我想问的是,哪种代码是计算the年的最佳方法。
正确的实现是:
public static boolean isLeapYear(int year) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365; }
但是,如果您要重新发明轮子,那么:
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; } }