有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java支付计算器未正确重置

因此,当你按下重置按钮或出现错误消息后,所有值都变为空白,但当你继续使用程序时,它们会继续添加,但它们应该重新开始

    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;
            }

        }
    } 

我希望在点击重置按钮或单击错误消息中的“确定”后,所有值都会完全重置


共 (1) 个答案

  1. # 1 楼答案

    只需将purchase = 0;行添加到catch语句中,就可以了。您可能希望在catch语句中添加一个numitems = 0;