gpt4 book ai didi

java - 为什么我的程序只输出一个结果而不是五个?

转载 作者:行者123 更新时间:2023-11-30 06:34:23 24 4
gpt4 key购买 nike

/*
*Find if a year is leap or not
*/

public class LeapYear{

private static int leapYear;

public void setLeapYear(int leapYear){

this.leapYear = leapYear;

}// end method


public static void main (String[] args) {
LeapYear leap = new LeapYear();
leap.setLeapYear(2010);
leap.setLeapYear(2008);
leap.setLeapYear(1900);
leap.setLeapYear(2000);
leap.setLeapYear(1565);

// Is it Divisible by 4?
if (leapYear % 4 == 0) {

// Is it Divisible by 4 but not 100?
if (leapYear % 100 != 0) {
System.out.println(leapYear + ": is a leap year.");
}
// Is it Divisible by 4 and 100 and 400?
else if (leapYear % 400 == 0) {
System.out.println(leapYear + ": is a leap year.");
}
// It is Divisible by 4 and 100 but not 400!
else {
System.out.println(leapYear + ": is not a leap year.");
}
}
// It is not divisible by 4.
else {
System.out.println(leapYear + ": is not a leap year.");
}
}
}

我是 Java 的新手,我编写了这段代码,以便它可以调用所有五年的 boolean 值并为所有这些值生成答案。但是它只调用最后一个。我该怎么做才对?

最佳答案

问题1

setLeapYear 的前四次调用:

leap.setLeapYear(2010);    // leap.leapYear = 2010;
leap.setLeapYear(2008); // leap.leapYear = 2008;
leap.setLeapYear(1900); // leap.leapYear = 1900;
leap.setLeapYear(2000); // leap.leapYear = 2000;

被最后一个覆盖:

leap.setLeapYear(1565);    // leap.leapYear = 1565;

我可能会编写一个名为 isLeapYear(int year) 的 boolean 方法并执行

System.out.println(isLeapYear(2010));
System.out.println(isLeapYear(2008));
...


问题2

leapYearstatic,所以你不需要/不应该做 LeapYear leap = new LeapYear();(或者,你应该删除 static 修饰符)。

关于java - 为什么我的程序只输出一个结果而不是五个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7063949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com