【发布时间】:2026-01-03 16:20:05
【问题描述】:
import javax.swing.JOptionPane;
int year;
boolean is_leap_year(int year)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
return true;
else
return false;
}
void setup ()
{
String answer = JOptionPane.showInputDialog("Enter a year or a negative number to test");
year = Integer.parseInt(answer);
while (year > 0) {
boolean b = is_leap_year(year);
if (b == true) {
println( year + " is a leap year");
}
else{
println( year + " is Not a leap year");
answer = JOptionPane.showInputDialog("Enter a year or a negative number to test");
year = Integer.parseInt(answer);
}
}
}
我编写了函数 is_leap_year 来测试输入是否是闰年。但是,程序不会因为一个错误而运行。
(第 3 行)“此方法必须返回布尔类型的结果。”
我不是已经这样做了吗,因为我将 boolean 作为函数类型放在标题中?我还将 return true 作为 if 语句的块。
另外,我不确定是否可以从设置中正确调用该函数。我觉得我好像错过了什么。
任何澄清将不胜感激。
编辑:(第 7 行和第 8 行)我完成了它并添加了 else 以返回 false。 出于某种原因,当我输入 2000 时,在多行中打印“2000 年是闰年”后处理崩溃。是否存在无限循环?我该如何解决?
【问题讨论】:
-
非闰年你的方法会返回什么值?
-
哦,哇,我完全忘记了。我猜我应该写 else() return false。
-
@PM77-1 嘿,我输入了 else 语句返回 false,但打印多行后处理崩溃。是否存在某种无限循环?
标签: function processing call