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

时间:2011-08-15 10:31:48

标签: java

/*
 *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的新手,我编写了这段代码,因此它会将所有五年的布尔值调用并生成所有这些代码的答案。但是它只调用最后一个。我该怎么做?

3 个答案:

答案 0 :(得分:3)

问题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)的布尔方法并执行

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


问题2

leapYearstatic,因此您不需要/不应该执行LeapYear leap = new LeapYear();(或者,您应该删除static修饰符)。

答案 1 :(得分:1)

您需要每年使用单独的对象,或者至少在您创建该年份的对象时调用闰年检查方法。

您所拥有的是对函数的一系列调用,该函数为同一对象的属性赋值。因此,只有最后一个语句才有效,因为先前的值会被覆盖。

另外请注意,您的代码似乎没有正确组织。乳清你在Main进行检查,似乎leapYear没有在任何地方定义。

也许,您可能想要定义一个函数,该函数返回true / false,具体取决于传递参数的值或对象中存储的年份值。

代码可能如下所示:

leap.setLeapYear(2010);    // leap.leapYear = 2010;
System.out.println(leap.isLeapYear());

leap.setLeapYear(2008);    // leap.leapYear = 2008;
System.out.println(leap.isLeapYear());
leap.setLeapYear(1900);    // leap.leapYear = 1900;
System.out.println(leap.isLeapYear());
leap.setLeapYear(2000);
System.out.println(leap.isLeapYear());
leap.setLeapYear(1565);
System.out.println(leap.isLeapYear());

您必须通过将main中的检查移动到该函数来定义isLeapYear()。

答案 2 :(得分:1)

我倾向于在if语句中按400到4的顺序编写测试:

String result;
if (year % 400 == 0) {
    result = "is a leap year.";
} else if (year % 100 == 0) {
    result = "is not a leap year.";
} else if (year % 4 == 0) {
    result = "is a leap year.";
} else {
    result = "is not a leap year.";
}
System.out.println(year + ": " + result);