在日期类中,写构造函数时先调用了日期类的方法判断
public Date(String date) {
if (isValidDate(date)) {
date = this.date;
}
}
现在我要在测试类中,让用户输入日期,默认为当前日期,若用户输入的日期不正确,则一直到用户输入正确为止,这样的话也就是说只有输入正确了才会构造日期类函数成功,但是我要判断是否正确必须要先构造才可以调用方法判断啊?怎么解决呢?
public Date(String date) {
if (isValidDate(date)) {
date = this.date;
}
else
throw Exception("invaliddate");
}
主程序
Date date = null;
while (date == null)
{
try
{
String s = input.readLine();
date = new Date(s);
}
catch {}
}
你直接写个验证日期格式化判断的工具类, 就不好了?
以下是方法体:
public static Date getDate(String txt){
if(txt != null && txt.matches("\\d{4}-\\d{2}-\\d{2}")){
return Date.valueOf(txt);
}
return null;
}
在调用的函数里,直接判断是否为空, 就完事了!