Java平闰年判断的两种方法

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




普通方法:

import java.util.Scanner;
public class Bissextile{
	public static void main(String[] args){
        Scanner input=new Scanner(System.in);//声明扫描仪变量
        System.out.println("请输入年份");//系统提示输入年份
        try{ //监听异常
        while(true){  //不断读取用户输入的值
            int years=input.nextInt();//取得下一行输入的年份值
            if (years<1000||years>9999)
                 System.out.println("请输入大于1000小于9999的年份");
            else if(years % 4 == 0 && years % 100 != 0 || years % 400 == 0){  //平闰年判断算法
                      System.out.println(years+"年是闰年");
                    }
            else {
                   System.out.println(years+"年是平年");
                }
            }
         }
        catch(Exception e){  //异常处理
    		System.out.println("请正确输入");
    		e.printStackTrace();  //打印异常信息在程序中出错的位置及原因
        }
     }
}  

一般函数/方法:

import java.util.Scanner;
public class Bissextile {
	boolean bissextile(int year){  //创建boolean类型的方法
		if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){  //平闰年判断算法
			return true;
		}
		else{
			return false;
		}
	}
	public static void main(String[] args){
		Bissextile b=new Bissextile();  //创建对象
		Scanner input=new Scanner(System.in);//声明扫描仪变量
		System.out.println("请输入年份");//系统提示输入年份
		try{
		while(true){  //不断读取用户输入的值
		int year1=input.nextInt();//取得下一行输入的年份值
		if (year1<1000||year1>9999){
			System.out.println("请输入大于1000小于9999的年份");
		}
		else if(b.bissextile(year1)){  //对象调用bissextile方法
			System.out.println(year1+"是闰年");
		}
		else{
			System.out.println(year1+"是平年");
				}
			}
		}
		catch(Exception e){  //异常处理
    		     System.out.println("请正确输入");
    		     e.printStackTrace();  //打印异常信息在程序中出错的位置及原因
		}
	}
}

注解:第二种方法用到了面向对象的思想

原文链接:https://www.idaobin.com/archives/310.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

× 5 = 40