Payment calculator does not reset properly

J. Sack :

So after you hit the reset button or have an error message all the values turn blank but keep getting added onto when you continue to use the program but they are supposed to start over.

    public GroceryCalc() {
    initComponents();

    purchase = 0;
    numitems = 0;

 }

 public void recordPurchase(double item_price) {
    purchase = purchase + item_price;
    numitems++;
 }

public double getPurchase() {
    return purchase;
}

public int getItems() {
    return numitems;
}      
 private void 
   Checkout_ButtonActionPerformed(java.awt.event.ActionEvent 
 evt) {
    double item_price;
    String purchase_string;
    String num_items_string;
    String item_price_string = "";
    NumberFormat n = NumberFormat.getCurrencyInstance();
    boolean keep_purchasing = true;

    while (keep_purchasing) {
        try {
            item_price_string = JOptionPane.showInputDialog(null, 
  "Enter Item Price", "Enter Price", JOptionPane.PLAIN_MESSAGE);
            if ((item_price_string != null) && 
  (item_price_string.length() > 0)) {
                item_price = Double.parseDouble(item_price_string);
                recordPurchase(item_price);
                purchase_string = n.format(purchase);
                num_items_string = Integer.toString(numitems);
                Item_Price_Text.setText(n.format(item_price));
                Sub_Total_Text.setText(purchase_string);
                Num_Items_Text.setText(num_items_string);

            } else {
                keep_purchasing = false;
                Sales_Tax_Text.setText(n.format(purchase * 0.065));
                Total_Sale_Text.setText(n.format(purchase + purchase 
  * 0.065));

            }

        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Your input must be 
   numeric!", "Bad Data!", JOptionPane.ERROR_MESSAGE);
            Item_Price_Text.setText("");
            Sub_Total_Text.setText("");
            Num_Items_Text.setText("");
            Sales_Tax_Text.setText("");
            Total_Sale_Text.setText("");
            if (item_price_string.isEmpty()) {
                return;
            }

        }
    } 

I expect all the values to fully reset after hitting the reset button or clicking "ok" from error message

Henrique Sabino :

just add the line purchase = 0; to your catch statement and it should be fine. You may want all well add a numitems = 0; to the catch statement.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166647&siteId=1