Create a program in Java. If a year is a leap year, return true; otherwise, return false

This is my code

public class Leapyear{
  public static void main(String []args){
    for(int year =2000; year <=2020; year++){
      if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
        System.out.println("Year " + year + " is a leap year");
      else
        System.out.println("Year " + year + " is not a leap year");
}

But the problem is: if it's not a leap year, I don't know how to return true. If it's not a leap year, I don't know how to return false

Solution

You can create a method to determine whether a year is a leap year like this.

public class Leapyear{
    public static void main(String []args){
        for(int year =2000; year <=2020; year++){
            if(isLeapYear(year)) {
              System.out.println("Year " + year + " is a leap year");
            else
              System.out.println("Year " + year + " is not a leap year"); 
        }
     }

    public static boolean isLeapYear(int year) {
        return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)) /* It will return boolean value (true or false) */
    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>