如何使用try / catch验证用户输入并将结果传递给构造函数?

时间:2019-03-03 19:51:20

标签: java

我目前无法尝试验证用户输入。问题是,每当我实现try / catch时,就永远不会达到我要创建的新对象中的匹配值。在以下情况下,我尝试使用“ productName”和“ purchaseName”:1无法留空,并以规定的格式(MM / dd / yyyy)要求日期。

public class ManagePurchases {

    public static void main (String [] args) throws Exception { 
        ArrayList<Purchase> purchases = new ArrayList<Purchase>();
        Scanner input = new Scanner (System.in);
        int choice = 0;
        final String fileName = "purchases.txt";
        boolean valid = false;

        do {
            System.out.println("1) Add a purchase");
            System.out.println("2) Display all purchases");
            System.out.println("3) Exit");
            choice = input.nextInt();

            switch (choice){
                case 1: 
                    System.out.println("Enter a product name.");
                    String newProduct = input.next();
                    System.out.println("Enter a store name.");
                    String newStore = input.next();
                    System.out.println("Enter a Date (like 03/19/1996)");
                    String str = input.next(); // get string for date
                    DateTimeFormatter dt = DateTimeFormatter.ofPattern("MM/dd/yyyy"); // set string format
                    LocalDate newDate = LocalDate.parse(str,dt); // convert our string to local date
                    System.out.println("Enter the cost.");
                    double newCost = input.nextDouble();
                    Purchase purchase = new Purchase(newProduct, newStore, newDate, newCost);
                    purchases.add(purchase);
                    break;
                case 2:
                    System.out.println(purchases);
                    break;
                case 3:
                    java.io.File file = new java.io.File(fileName);
                    if (file.exists()) {
                        System.out.println("File already exist");
                        System.out.println("Thank you for using the Purchase Tracker.");
                        System.exit(0);
                    }
                    if (purchases.isEmpty() == false) {
                    try (java.io.PrintWriter output = new java.io.PrintWriter(fileName)) {
                            for (int i = 0; i < purchases.size(); i++)
                            output.println(purchases.get(i));
                            output.close();
                }
                    System.out.println("Thank you for using the Purchase Tracker.");
                    System.exit(0); 

                  } try (Scanner scanner = new Scanner (new File(fileName))){
                    while (scanner.hasNext()) {
                        newProduct = input.next();
                        newStore = input.next();
                        str = input.next(); // get string for date
                        dt = DateTimeFormatter.ofPattern("MM/dd/yyyy");
                        newDate = LocalDate.parse(str, dt);
                        newCost = input.nextDouble();
                        purchase = new Purchase(newProduct, newStore, newDate, newCost);
                        purchases.add(purchase);
                    } 

                  } catch (FileNotFoundException e) {
                      System.out.println("Cant find / open text file: " + fileName);
                  }
                    input.close();
                    break;
                default:
                    System.out.println("Invalid selection. Enter a value between 1 - 2, or press 3 to exit.");
                }
        } while (choice > 0);   
    }   
}

这是我的“购买”类,我正在尝试将值传递回。谢谢你的指点,对不起,如果我把事情弄复杂了。我的应用程序运行正常,只是我目前无法检查用户是否输入了无效数据,并提示他们再试一次。

公共类购买{

private String productName;
private String storeName;
private LocalDate purchaseDate = LocalDate.now();
private double cost;

// Default Constructor
public Purchase(String newProduct, String newStore, LocalDate newDate, double newCost) {
    try {
        setProductName(newProduct);
        setStoreName(newStore);
        setPurchaseDate(newDate);
        setCost(newCost);
    } catch (IllegalPurchaseArgumentException ex) {
        System.out.println("Invalid value");
    }

}

public String getProductName() {
    return productName;
}

public void setProductName(String newProduct) throws IllegalPurchaseArgumentException {
    if (newProduct != null && newProduct.length() > 1) {
        this.productName = newProduct;
    } else {
        throw new IllegalPurchaseArgumentException (newProduct);
    }
}

public String getStoreName() {
    return storeName;
}

public void setStoreName(String newStore) throws IllegalPurchaseArgumentException {
    if (newStore != null && newStore.length() > 1) {
        this.storeName = newStore;
    } else {
         throw new IllegalPurchaseArgumentException (newStore); 
    }
}

public LocalDate getPurchaseDate() {
    return purchaseDate;
}

public void setPurchaseDate(LocalDate newDate) throws IllegalPurchaseArgumentException {
    if(newDate != null) {
    this.purchaseDate = newDate;
    } else {
        throw new IllegalPurchaseArgumentException();
    }
}

public double getCost() {
    return cost;
}

public void setCost(double newCost) throws IllegalPurchaseArgumentException {
    if (newCost >= 0) {
    this.cost = newCost;
    } else {
        throw new IllegalPurchaseArgumentException();
    }
}

@Override
public String toString() {
    return "Purchase [product name = " + productName + ", storeName = " +
            storeName + ", purchaseDate = " + purchaseDate + 
            ", cost = " + cost + "]";
}

0 个答案:

没有答案