【发布时间】:2013-11-21 13:23:29
【问题描述】:
我正在用 Java 编写一个程序来根据公历接受和验证日期。我的 public boolean setDate(String aDate) 函数输入不正确,假设将 boolean goodDate 变量更改为 false。假设该变量告诉 toString 函数在调用时输出“无效条目”,但它没有。我的 public boolean setDate(int d, int m, int y) 函数工作正常。我只将问题部分作为一段很长的代码包含在内。谢谢
public boolean setDate(int day, int month, int year){
// If 1 <= day <= 31, 1 <= month <= 12, and 0 <= year <= 9999 & the day match with the month
// then set object to this date and return true
// Otherwise,return false (and do nothing)
boolean correct = isTrueDate(day, month, year);
if(correct){
this.day = day;
this.month = month;
this.year = year;
return true;
}else{
goodDate = false;
return false;
}
//return false;
}
public boolean setDate(String aDate){
// If aDate is of the form "dd/mm/yyyy" or "d/mm/yyyy"
// Then set the object to this date and return true.
// Otherwise, return false (and do nothing)
Date d = new Date(aDate);
boolean correct = isTrueDate(d.day, d.month, d.year);
if(correct){
this.day = d.day;
this.month = d.month;
this.year = d.year;
return true;
}else{
goodDate = false;
return false;
}
}
public String toString(){
// outputs a String of the form "dd/mm/yyyy"
// where dd must be 2 digits (with leading zero if needed)
// mm must be 2 digits (with leading zero if needed)
// yyyy must be 4 digits (with leading zeros if needed)
String day1;
String month1;
String year1;
if(day<10){
day1 = "0" + Integer.toString(this.day);
} else{
day1 = Integer.toString(this.day);
}
if(month<10){
month1 = "0" + Integer.toString(this.month);
} else{
month1 = Integer.toString(this.month);
}
if(year<10){
year1 = "00" + Integer.toString(this.year);
} else{
year1 = Integer.toString(this.year);
}
if(goodDate){
return day1 +"/" +month1 +"/" + year1;
}else{
goodDate = true;
return "Invalid Entry";
}
}
谢谢
【问题讨论】:
标签: java date boolean comparable