Java实现闰年案例的两种方法

前言

   明哥教学案例,计算闰年,两种实现方式

方式一

package com.mg.one;

import java.util.Scanner;

/**
 * 类名:AleapYear
 * 包名:com.mg.one
 * 创建时间:2020/6/29 14:22
 * 创建人: 明哥
 * 描述:   普通方式实现
 *
 *  判断条件
 *     1、能被4整除,而且不能被100整除
 *     2、能被400整除
 *     3、 && 的优先级高于 ||

 **/
public class AleapYear {
    public static void main(String[] args) {
        System.out.println("请输入年份:");
        //   键盘动态输入
        Scanner input =new Scanner(System.in);
        // 捕捉异常
        try {
             // 循环读取用户输入的值
             while (true){
                 //  循环读取用户输入的值
                int year=input.nextInt();
                 if (year<1000 || year >9999)
                     System.out.println("请输入大于1000小于9999的年份");
                 else if (year %4==0 && year %100 !=0 || year %400==0){
                     System.out.println(year+"年,是闰年");
                 }else {
                     System.out.println(year+"年,是平年");
                 }

             }
        }catch (Exception e){
            System.out.println("请输入正确年份:");
            e.getStackTrace();
        }
    }
}

 

方式二

package com.mg.one;

import java.util.Scanner;

/**
 * 类名:AleapYearTwo
 * 包名:com.mg.one
 * 创建时间:2020/6/29 14:34
 * 创建人: 明哥
 * 描述:  实现方式二  面向对象的方式
 **/
public class AleapYearTwo {
    // 创建boolean tocalculate
    boolean tocalculate(int year){
        // 算法
        if (year %4==0 && year %100 !=0 || year %400==0){
            return  true;
        }else {
            return  false;
        }
    }

    public static void main(String[] args) {
        // 实例化AleapYearTwo对象
        AleapYearTwo yearTwo=new AleapYearTwo();
        //键盘动态输入
        Scanner input=new Scanner(System.in);
        //提示语句
        System.out.println("请输入年份");
        // 捕获异常
        try{
            // 循环读取用户输入的值
            while (true) {
                int year=input.nextInt();
                if (year<1000 || year >9999)
                    System.out.println("请输入大于1000小于9999的年份");
                 else if (yearTwo.tocalculate(year)){
                    System.out.println(year+"年,是闰年");
                }else {
                    System.out.println(year+"年,是平年");
                }

            }
        }catch (Exception e){
            System.out.println("请输入正确年份");
            e.getStackTrace();
        }

    }
}

 

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈老说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值