【发布时间】:2021-01-28 08:47:58
【问题描述】:
代码在第一年是闰年时有效,所以如果我说年份是 2004 年,它将返回 2008 年,但当起始年不是闰年时,它什么也不返回。例如,如果给定年份是 2001、2002 或 2003 年,下一个闰年将是 2004 年,我将如何输出。我知道 while 循环是有道理的,但我不知道在里面放什么。另外我只能使用基本的 java 格式,所以没有像 java.time.Year 这样的输入类
public static boolean leapYear(int year) {
boolean isLeap = true;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
isLeap = true;
else
isLeap = false;
} else
isLeap = true;
} else {
isLeap = false;
}
return isLeap;
}
public static int nextLeapYear(int year) {
int nextLeap = 0;
if (leapYear(year)) {
nextLeap = nextLeap + 4;
} else {
while (!leapYear(year)) {
nextLeap++;
}
nextLeap += 1;
}
year += nextLeap;
return year;
}
【问题讨论】:
-
您也可以接受自己的答案(一段时间后,我想是 12 小时)。
-
如果这是一个练习,那是一个很好的练习。对于生产代码,我们不会也不应该自己计算闰年,而应该将其留给`Year.isLeap() 或其他好的库方法。
标签: java date for-loop while-loop leap-year