/* *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的新手,所以我编写了这段代码,以便将这整个五年都称为布尔值,并为所有布尔值生成答案。但是,它仅调用最后一个。我该怎么做呢?
您每年需要使用单独的对象,或者至少在创建该年份的对象后立即调用the年检查方法。
您所拥有的是对函数的一系列调用,该函数将值分配给同一对象的属性。因此,只有最后一条语句才起作用,因为先前的值将被覆盖。
另外请注意,您的代码似乎没有正确组织。乳清您在Main中进行检查,似乎leapYear没有在任何地方定义。
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()。