Getter方法返回错误值

时间:2019-04-28 20:05:59

标签: java date constructor instance-variables

我有一个构造函数,该构造函数接受一个String并将该String转换为日期。但是,当我运行主代码时,会得到不正确的随机日期。我做了一个测试类,只是为了测试构造函数中的代码,并且一切运行正常,我得到了适当的输出。但是,我的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。我不知道这个日期是哪里来的。

1 个答案:

答案 0 :(得分:2)

如果您的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转换