gpt4 book ai didi

java - Getter 方法返回错误值

转载 作者:行者123 更新时间:2023-12-02 01:31:52 24 4
gpt4 key购买 nike

我有一个构造函数,它接受一个字符串并将该字符串转换为日期。但是,当我运行主代码时,我得到不正确的随机日期。我创建了一个测试类只是为了测试构造函数中的代码,一切运行正常,我得到了适当的输出。但是,我的 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());

this answer 转换

关于java - Getter 方法返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55894164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com