java - Getter 方法返回错误的值
问题描述
我有一个构造函数,它接受一个字符串并将该字符串转换为日期。但是,当我运行我的主代码时,我得到不正确的随机日期。我创建了一个测试类,只是为了测试构造函数中的代码,一切运行良好,我得到了适当的输出。但是,我的 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;
}
}
所以假设我输入日期 1/10/1997,我会得到日期 4/20/0007。我不知道这个日期是从哪里来的。
解决方案
如果您的 Java 版本支持它,我建议您使用 LocalDate 而不是 Calendar/Date
private LocalDate dateOfSale;
...
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]);
dateOfSale = LocalDate.of(year, month, day);
...
}
如果您需要dateOfSale
声明,Date
您仍然可以跳过Calendar
LocalDate localDate = LocalDate.of(year, month, day);
dateOfSale = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
推荐阅读
- reactjs - React - TypeError:setActiveProject 不是函数
- r - R doParallel:即使它出现在环境中,函数也找不到函数
- php - 广播或事件不做任何事情
- python - 如何将标题文本添加到来自 figurefactory 的两个带注释的热图?
- c++ - std::deque: push_front() 和 push_back() 如何在 O(1) 中实现?
- r - 使用 RSelenium 和 Docker 容器下载数据(makeFirefoxProfile 和 mime 类型)
- dialogflow-es - 如何从整个后端的必需参数更改 SlotFilling 和提示问题
- selenium-chromedriver - TestNG 没有为 Firefox 驱动程序运行 @Test -- Chrome 工作
- java - JSP 正在下载而不是渲染
- node.js - 启动另一个具有不同版本的节点子进程