简体   繁体   中英

Leap year HW beginner in java

I have to create a piece of code that displays which years are leap years and which are not. I enter non leap years but the program still displays them as leap year. How do i get the program to return false for non leap years, using only one if statement.We've already been giving a tester class.

public boolean isLeapYear() {
    // your code here 
    if  ((year % 4 == 0) || (year % 400 == 0) & (year % 100 != 0))  
    {
       return true; } {
       return false;
    }

}

I expect the output to say thats not a leap year on non leap yars. some of the errors i have received are missing return statement and illegal start of expression.

When doing expressions like this, order is important. When year % 4 == 0 is encountered, it will be true if the year is also a century year. So the rest of the expression won't be evaluated. Try putting the first and third expression together in parens and the middle one by itself. Note also that you can just use return followed by the expression since the expression evaluates to true or false.

Instead of

 if (a == true) {
     return true;
 } 
 return false;

Just do


return a;

The expression should be.

(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM