前言
明哥教学案例,计算闰年,两种实现方式
方式一
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();
}
}
}