Determine whether a given year is a leap year (Java programming classical case)

A user input year, the year the program can determine whether the input is a leap year, as follows:

import java.util.Scanner;
/**
 * 判断某一年是否为闰年
 */
public class Example {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入一个年份:");	//向控制台输出一个提示信息
        long year;
        try {
            year = scan.nextLong();
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { // 是闰年
                System.out.print(year + "是闰年!");
            } else { 								// 不是闰年
                System.out.print(year + "不是闰年!");
            }
        } catch (Exception e) {
            System.out.println("您输入的不是有效的年份!");
        }
    }
}

Execution results as follows:
Here Insert Picture Description
if the present example is a leap year by determining if statement determines whether a year is a leap year, to meet two conditions, one is divisible by 4 but not divisible by 100, the other 400 can be an integer out.
Leap year judging formula:! Year% 4 == 0 && year% 100 = 0 || year% 400 == 0

Guess you like

Origin blog.csdn.net/cui_yonghua/article/details/92385937