Getter方法返回错误的值[关闭]

问题描述 投票:0回答:1

我有一个构造函数,它接受一个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;
  }
}

所以我想说我在1997年1月10日输入日期,我将获得日期4/20/0007。我不知道这个日期的来源。

java date constructor instance-variables
1个回答
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转换

© www.soinside.com 2019 - 2024. All rights reserved.