日期:2014-05-20  浏览次数:20945 次

java小程序,判断输入的年份是否合法,动态输入,高手进
java小程序,判断输入的年份是否合法,动态输入,用args[]判断,不用什么其他的类。。。请高手编一下

------解决方案--------------------
你可以写javascript,在页面检验就可以了呀 ?
------解决方案--------------------
class TestDate
{
static boolean isLeapYear(int aYear) //判断是否是闰年,不考虑年份的负值之类的
{
if ( (aYear%4==0 && aYear%100!=0) || (aYear%400==0) ){
return true;
}

return false;
}

static boolean isAvailabilityMonth(int aMonth) //判断月份是否正确
{
return (aMonth <13 && aMonth > 0) ? true : false ;
}

static boolean isAvailabilityDay(int aYear,int aMonth,int aDay) //判断日期是否有效
{

int nmaxday;

if (!isAvailabilityMonth(aMonth)) return false ;

switch(aMonth)
{
case 4:
case 6:
case 9:
case 11:
nmaxday=30;
break;

case 2:
if(isLeapYear(aYear)){
nmaxday=29;
} else {
nmaxday = 28;
}

break;

default:
nmaxday=31;
}

if(aDay > nmaxday || aDay < 1 ){
return false;
}

return true;

}

public static void main(String args[]){

if ( args.length == 3) {

int year = Integer.parseInt(args[0]);
int month = Integer.parseInt(args[1]);
int day = Integer.parseInt(args[2]);

if (isAvailabilityDay(year , month , day )){
System.out.println( "输入的日期正确 ") ;
}else{
System.out.println( "输入的日期不正确 ") ;
}

}else{
System.out.println( "输入的参数不为三个 ") ;
}
}
}
其实就是在你的程序基础上改得。用1000.2.29 和 2000.2.29 测试一下。
你原来的程序,把判断闰年的函数以及把判断日期的函数写到main函数里了,这是不对的。另外,有些地方,比较用 == 写成了= 。还有输入的args参数是String ,而你比较日期年份时,方法的参数是int,因此需要转换一下。
慢慢写,尝试读一些编译时提示的错误,然后查一查,进步会比较大。
------解决方案--------------------
java 判断日期的正则表达式
java 判断日期的正则表达式:
此例为Struts中的应用,格式为:2006-10-01
private boolean Check()
{
if( theForm.getStarttime()!= " "&&! " ".equals(theForm.getStarttime())&&theForm.getEndtime()!= " "&&! " ".equals(theForm.getEndtime()))
{
boolean b=theForm.getStarttime().matches( "[1-9][0-9]{3}\\-(0[0-9]|1[0-2])\\-(0[0-9]|1[0-9]|2[0-9]|3[0-1]) ");
boolean bn=theForm.getEndtime().matches( "[1-9][0-9]{3}\\-(0[0-9]|1[0-2])\\-(0[0-9]|1[0-9]|2[0-9]|3[0-1]) ");
if(!b){msg = "日期格式错误!!! " ;
return false ;
}
if(!bn){msg = "日期格式错误!!! " ;
return false ;
}

}
return true ;
}