Java小程序之——判断输入的某个年份是否是闰年

编写程序,判断给定的某个年份是否是闰年。

      闰年的判断规则如下:

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

     2)若某个年份能被400整除,则也是闰年。

程序一:

package exercise;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IsLeapYear {
public static boolean isNum(String str){
boolean isNum=true;
for(int i=0;i<str.length();i++){
//mark if the year is a number;
isNum=false;
if(str.codePointAt(i)>47&&str.codePointAt(i)<58){
isNum
=true;
}
if(isNum==false){
break;
}

}
//for

return isNum;
}

public void isHeapYear(){
int year=0;

System.out.println(
"Please input the year you want to judge:");

Scanner in
=new Scanner(System.in);
String temp
=in.next();

if(!isNum(temp)){
System.out.println(
"the year you input is not valid");
}
else{
year
=Integer.parseInt(temp);
if(year<1980||year>2050){
System.out.println(
"the year you input is not in the scale");
System.exit(
1);
}
else if((year%4==0&&year%100!=0)||year%400==0){
System.out.println(year
+" is a leap year");
}
else{
System.out.println(year
+" is not a leap year");
}
}

}
public static void main(String[] args){

new IsLeapYear().isHeapYear();

}
}

  程序二:

package exercise;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IsLeapYearReg {

public static boolean isNum(String str){
Pattern p
= Pattern.compile("[0-9]*");
Matcher isNum
= p.matcher(str);
if(isNum.matches()){
return true;
}
else{
return false;
}
}

public void isHeapYear(){
int year=0;

System.out.println(
"Please input the year you want to judge:");

Scanner in
=new Scanner(System.in);
String temp
=in.next();

if(!isNum(temp)){
System.out.println(
"the year you input is not valid");
}
else{
year
=Integer.parseInt(temp);
if(year<1980||year>2050){
System.out.println(
"the year you input is not in the scale");
System.exit(
1);
}
else if((year%4==0&&year%100!=0)||year%400==0){
System.out.println(year
+" is a leap year");
}
else{
System.out.println(year
+" is not a leap year");
}
}
}

public static void main(String[] args){
new IsLeapYearReg().isHeapYear();
}
}

跟我走啊~~
原文地址:https://www.cnblogs.com/wrh526/p/2115031.html