Java基础(1)_判断闰年

541 阅读1分钟

判断闰年

闰年的判断规则如下:

(1) 若某个年份能被 4 整除但不能被 100 整除,则是闰年。
(2) 若某个年份能被 400 整除,则也是闰年。

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个年份:");
        // 将年份放在自变量leapYear中
        int leapYear = sc.nextInt();
        if (isLeapYear(leapYear)) {
            System.out.println(leapYear + "是闰年");
        } else {
            System.out.println(leapYear + "不是闰年");
        }
    }

    public static boolean isLeapYear(int year) {
        return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
    }
}