首页 > 编程 > Java > 正文

Java平闰年判断的方法总结

2019-11-26 10:14:59
字体:
来源:转载
供稿:网友

普通方法:

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(); //打印异常信息在程序中出错的位置及原因		}	}}

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表