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

      闰年的判断规则如下:

     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/archive/2011/07/23/2115031.html

Logo

昇腾计算产业是基于昇腾系列(HUAWEI Ascend)处理器和基础软件构建的全栈 AI计算基础设施、行业应用及服务,https://devpress.csdn.net/organization/setting/general/146749包括昇腾系列处理器、系列硬件、CANN、AI计算框架、应用使能、开发工具链、管理运维工具、行业应用及服务等全产业链

更多推荐