如何在构造函数中设置过期日期?

时间:2015-11-26 19:14:16

标签: java

我正在尝试制作一个TravelCard课程,该课程还应检查该卡是否仍然可行(未过期)。但我有这个错误

  

未报告的异常ParseExeption;必须被抓住或宣布被抛出

在这一行

this.expirationDate = sdf.parse(expiry);

如何在构造函数中设置过期日期?

我之前从未使用过日期,因为有人会注意到。而且我在Java方面也相当新。

package something;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TravelCard {
    private double balance;
    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    private Date expirationDate;
    private Date today = Calendar.getInstance().getTime();

    public TravelCard(double balance, String expiry){
        sdf.setLenient(false);
        this.balance = balance;
        this.expirationDate = sdf.parse(expiry);
    }

    public void pay(double price){
        if (today.before(expirationDate)){
            if(this.balance >= price){
                this.balance -= price;
            }
            else {
                System.out.println("Insufficient funds");
            }
        }
        else {
            System.out.println("Card expired");
        }
    }

    public double getBalance(){
        return balance;
    }

}

3 个答案:

答案 0 :(得分:1)

这意味着,parse()方法会抛出已检查的异常,catch异常或throw

捕捉异常的方法:

public void TravelCard(double balance, String expiry){
        sdf.setLenient(false);
        this.balance = balance;
         try {
             this.expirationDate = sdf.parse(expiry);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

抛出异常的方法:

 public void TravelCard(double balance, String expiry) throws ParseException{

答案 1 :(得分:1)

让构造函数接受Date参数(expirationDate)而不是String参数(expiry)会更好。并在调用TravelCard构造函数之前解析String。如果您无法解析到期字符串,则无法创建具有有效到期日期的TravelCard对象。

public class TravelCard {
    private double balance;
    private final Date expirationDate;
    private final Date today = Calendar.getInstance().getTime();

    public TravelCard(final double balance, final Date expirationDate) {
        this.balance = balance;
        this.expirationDate = expirationDate;
    }

    // parsing the expiry String and then calling the constructor
    public static TravelCard createTravelCard(final double balance, final String expiry) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        Date expirationDate = sdf.parse(expiry)
        return new TravelCard(balance, expiry);
    }

    // examples
    TravelCard.createTravelCard(20.0, "26/11/2016"); // TravelCard created
    TravelCard.createTravelCard(20.0, "36/11/2016"); // throws ParseException 

答案 2 :(得分:0)

编译器试图告诉您sdf.parse(expiry)可能会失败。由于此方法(parse)明确throws类型ParseException的异常您必须将其放在try{..}catch(..){..}块中,或者将throws声明添加到构造函数中。