Java 程序:检查闰年

要理解此示例,您应了解以下Java编程主题


闰年是能被4整除的年份,但世纪年(以00结尾的年份)除外。世纪年只有能被400整除时才是闰年。

例如:Java程序判断闰年

public class Main {

  public static void main(String[] args) {

    // year to be checked
    int year = 1900;
    boolean leap = false;

    // if the year is divided by 4
    if (year % 4 == 0) {

      // if the year is century
      if (year % 100 == 0) {

        // if year is divided by 400
        // then it is a leap year
        if (year % 400 == 0)
          leap = true;
        else
          leap = false;
      }
      
      // if the year is not century
      else
        leap = true;
    }
    
    else
      leap = false;

    if (leap)
      System.out.println(year + " is a leap year.");
    else
      System.out.println(year + " is not a leap year.");
  }
}

输出

1900 is not a leap year.

在上面的例子中,我们检查年份1900是否为闰年。由于1900是世纪年(以00结尾),它必须能被4400整除才能成为闰年。

然而,1900不能被400整除。因此,它不是闰年。

现在,让我们将年份更改为2012。输出将是

2012 is a leap year.

在这里,2012不是世纪年。因此,要成为闰年,它只需要能被4整除。

由于2012能被4整除,所以它是闰年。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战