【发布时间】:2019-09-17 12:50:44
【问题描述】:
我有一个构造函数,它接受一个字符串并将该字符串转换为日期。但是,当我运行我的主代码时,我得到不正确的随机日期。我创建了一个测试类,只是为了测试构造函数中的代码,一切运行良好,我得到了适当的输出。但是,我的 getter 方法给了我错误的日期。此外,if 语句也没有检查我的参数的有效性。不知道如何解决它。
import java.util.Calendar;
import java.util.Date;
import java.lang.Integer;
public class RealEstateSale{
private String country;
private double price;
private Date dateOfSale;
CurrencyConverter cc = new CurrencyConverter();
public String getCountry(){
return country;
}
public RealEstateSale(double price){
this.price = price;
if(price < 0){
country = null;
}
}
public double getPrice(){
return price;
}
public RealEstateSale(String country, String date){
this.country = country;
String [] tokens = date.split("/");
int month = Integer.parseInt(tokens[0]);
int day = Integer.parseInt(tokens[1]);
int year = Integer.parseInt(tokens[2]);
Calendar dateMaker = Calendar.getInstance();
dateMaker.set(year, month-1, day);
dateOfSale = dateMaker.getTime();
if(0 > year || 0 > month || 0 > day){
this.country = null;
} else if (month > 11){
this.country = null;
} else if(day > 31){
this.country = null;
} else if (!cc.countryCodes.contains(country)){
this.country = null;
}
}
public Date getDate(){
return dateOfSale;
}
}
假设我输入的日期是 1997 年 1 月 10 日,我会得到 0007 年 4 月 20 日的日期。我不知道这个日期是从哪里来的。
【问题讨论】:
-
在争取时间之前是否需要致电
dateMaker.computeTime? -
我不这么认为。在我的测试代码中,我使用了完全相同的代码并且得到了正确的输出。我确定我用于日期的代码是正确的,我只是怀疑它与构造函数获取和设置日期的方式有关
-
我无法使用您发布的代码重现问题:ideone.com/e8xzhB。您能否添加一个可重现的可运行示例?
标签: java date constructor instance-variables