Home  >  Article  >  Java  >  Detailed explanation of the method to determine whether it is a leap year in Java

Detailed explanation of the method to determine whether it is a leap year in Java

尚
Original
2019-11-28 10:25:1311682browse

Detailed explanation of the method to determine whether it is a leap year in Java

Given a year, determine whether it is a leap year. The conditions are: (Recommended: java video tutorial)

A: It is divisible by 4 and not divisible by 100. Or

B: Divisible by 400.

Analysis:

First of all, A and B in the question are two options for judging whether a leap year is true, and they belong to the situation of "if not A, then B". It is often easy to think of the following structure here To solve this problem

if(判断条件A成立){
表达式1(为闰年)
}
else if(判断条件B成立){
表达式1(为闰年)
}

There is an implicit result here, what should we do if it is not a leap year?

In fact, it is very simple. Just add an else{(What should I do if it is not a leap year)} statement after the original structure

if(判断条件A成立){
表达式1(为闰年)
}
else if(判断条件B成立){
表达式1(为闰年)
}

. It seems to have added a very simple statement, but It is precisely because of this statement that the entire program becomes complete.

Example:

We first write the source program without adding the last else statement, test it in 2000 and 2001, and write the source program according to the if..else if.. structure The code is as follows:

package com.tencentos;
import java.util.Scanner;
public class Week1homework1 {
  public static void main(String[] args) {
    Scanner scan=new Scanner(System.in);
    System.out.print("Plese input the year:");
    int year=scan.nextInt();
    if(year%4==0 && year%100!=0){
       System.out.print("Congratulation! It's the leap year!");
    }else 
    if(year%400==0){
        System.out.print("Congratulation! It's the leap year!");
    }   
    scan.close();
  }
}

When "2000" is entered, everything goes as we want. The feedback that pops up in the control box is exactly what we want. The year 2000 is indeed a leap year.

Detailed explanation of the method to determine whether it is a leap year in Java

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of Detailed explanation of the method to determine whether it is a leap year in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn