我需要帮助让我的计算器工作 - NetBeans

时间:2012-06-05 17:12:47

标签: java swing netbeans jframe calculator

我正在尝试创建一个零售计算器,它将显示商品的销售价格。用户在文本框中输入项目的原始价格,并在另一个框中打折百分比。然后,用户单击“计算”按钮以获得答案。我的问题是我无法让程序计算出答案,而是收到了很多错误信息。我只看到一些行上的错误,但我无法弄清楚如何修复它们。以下是我的代码:

导入javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * 
 * @author Owner
 */
public class RetailCalcForm extends javax.swing.JFrame {

    private void close() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private static class number {

        public number() {
        }
    }

    private static class number2 {

        public number2() {
        }
    }

    /**
     * Creates new form RetailCalcForm
     */
    public RetailCalcForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        itemNameText = new javax.swing.JTextField();
        originalPriceText = new javax.swing.JTextField();
        percentDiscountedText = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        calculateButton = new javax.swing.JButton();
        salesPriceLabel = new javax.swing.JLabel();
        exitButton = new javax.swing.JButton();
        javax.swing.JComboBox departmentBox = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Item Name");

        jLabel2.setText("Original Price");

        jLabel3.setText("% Discounted");

        calculateButton.setText("Calculate Discount Price");
        calculateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calculateButtonActionPerformed(evt);
            }
        });

        salesPriceLabel.setText("Discounted Sales Price: ");

        exitButton.setText("Exit");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        departmentBox.setModel(new javax.swing.DefaultComboBoxModel(
                new String[] { "Electronics", "Toys", "Clothing", "Housewares",
                        "Garden" }));
        departmentBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                departmentBoxActionPerformed(evt);
            }
        });

        jLabel4.setText("Select Department");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
                getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                                .addGap(28, 28, 2Cool

                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(
                                                        layout.createSequentialGroup()
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(
                                                                                        jLabel2)
                                                                                .addComponent(
                                                                                        jLabel1))
                                                                .addContainerGap())
                                                .addGroup(
                                                        layout.createSequentialGroup()
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(
                                                                                        salesPriceLabel,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                        310,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                .addGroup(
                                                                                        layout.createSequentialGroup()
                                                                                                .addGroup(
                                                                                                        layout.createParallelGroup(
                                                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                                                .addComponent(
                                                                                                                        jLabel3)
                                                                                                                .addComponent(
                                                                                                                        jLabel4))
                                                                                                .addGap(26,
                                                                                                        26,
                                                                                                        26)
                                                                                                .addGroup(
                                                                                                        layout.createParallelGroup(
                                                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                                                .addComponent(
                                                                                                                        percentDiscountedText,
                                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                                        145,
                                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                                                .addComponent(
                                                                                                                        departmentBox,
                                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                                        105,
                                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                                                .addGroup(
                                                                                                                        layout.createSequentialGroup()
                                                                                                                                .addGroup(
                                                                                                                                        layout.createParallelGroup(
                                                                                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                                                                                .addComponent(
                                                                                                                                                        originalPriceText,
                                                                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                                                                        145,
                                                                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                                                                                .addComponent(
                                                                                                                                                        itemNameText,
                                                                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                                                                        145,
                                                                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                                                                                                .addPreferredGap(
                                                                                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                                                                                                        59,
                                                                                                                                        Short.MAX_VALUE)
                                                                                                                                .addComponent(
                                                                                                                                        calculateButton)))))
                                                                .addGap(0, 33,
                                                                        33))))
                .addGroup(
                        layout.createSequentialGroup().addGap(228, 228, 228)
                                .addComponent(exitButton)
                                .addGap(0, 0, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                                .addGap(69, 69, 69)
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.TRAILING)
                                                .addComponent(
                                                        departmentBox,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(jLabel4))
                                .addGap(35, 35, 35)
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.TRAILING)
                                                .addComponent(jLabel1)
                                                .addComponent(
                                                        itemNameText,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(37, 37, 37)
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jLabel2)
                                                .addComponent(
                                                        originalPriceText,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(26, 26, 26)
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.TRAILING)
                                                .addComponent(
                                                        percentDiscountedText,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(jLabel3))
                                .addGap(35, 35, 35)
                                .addComponent(salesPriceLabel)
                                .addPreferredGap(
                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                        44, Short.MAX_VALUE)
                                .addComponent(exitButton).addGap(26, 26, 26))
                .addGroup(
                        layout.createSequentialGroup()
                                .addGap(140, 140, 140)
                                .addComponent(calculateButton,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        87,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap()));

        pack();
    }// </editor-fold>

    private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
        int number1 = 0, number2 = 0;
        try (
            int = Integer.parseInt(
            this.originalPriceText.getText());
        catch (Excemption e) {
            JOptionPane.showMessageDialog(this, "Invalid Price Amount", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        try (
            int = Integer.parseInt(
            this.percentDiscountedText.getText());
        catch (Excemption e) {
            JOptionPane.showMessageDialog(this, "Invalid Discount Amount", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int answer = number1 / number2;
        this.salesPriceLabel.setText("Discounted Sales Price: " / answer);
    }

    private void departmentBoxActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {
        System.exit(0);
        close();

    }

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        // <editor-fold defaultstate="collapsed"
        // desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase
         * /tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
                    .getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RetailCalcForm.class.getName())
                    .log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RetailCalcForm.class.getName())
                    .log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RetailCalcForm.class.getName())
                    .log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RetailCalcForm.class.getName())
                    .log(java.util.logging.Level.SEVERE, null, ex);
        }
        // </editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new RetailCalcForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton calculateButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JTextField itemNameText;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField originalPriceText;
    private javax.swing.JTextField percentDiscountedText;
    private javax.swing.JLabel salesPriceLabel;
    // End of variables declaration
}

我将非常感谢能得到的任何帮助。

4 个答案:

答案 0 :(得分:3)

这是一个try catch块(你忘记用}

关闭try块
try {
    number1  = Integer.parseInt(this.percentDiscountedText.getText());
} catch (Exception e) {
    JOptionPane.showMessageDialog(this, "Invalid Discount Amount", "Error", JOptionPane.ERROR_MESSAGE);
    return;
}

并且例外不是 Excemption

<小时/> 您需要+而不是/来连接变量字符串:

this.salesPriceLabel.setText("Discounted Sales Price: " +  answer);

<小时/> 要创建一个整数,您需要一个名称。

int = Integer.parseInt("1"); ---> int name = Integer.parseInt("1");

但是在你的情况下,你不必创建一个新的int,我想你必须使用number1number2

<小时/> 我不知道这条线有什么问题。首先,我认为你必须用括号

替换Cool
.addGap(28, 28, 2Cool  ---> .addGap(28, 28, 2)

但计算器不再工作(java.lang.IllegalArgumentException: Following is not met: min<=pref<=max) 解决方案对我来说就是删除这一行。

答案 1 :(得分:2)

有一件事,try / catch块像所有其他块一样使用花括号,而不是括号。

try (
   // some code ...
) catch (Exception e) {
   // catch code here
}

什么时候应该

try {
   // some code ...
} catch (Exception e) {
   // catch code here
}

但更重要的是你的编码风格需要纠正。您似乎在屏幕上添加了大量代码,忽略了所有错误,直到您输入了整个内容,这就是灾难的秘诀。您需要在添加的每一行或两行代码后更正每个编译错误。除此之外,除了老鼠的错误之外,你几乎无法做到这一点。

答案 2 :(得分:2)

JFormattedTextField / JSpinnerNumber Formatter一起使用,而不是解析String

中的数字

答案 3 :(得分:1)

你在写 -

int=Integer.parseint(this.originalPriceText.getText()); 

哪个错了!它应该是 -

number1=Integer.parseint(this.originalPriceText.getText()); 

此外,try块被包裹在花括号内 -

try{
    // code goes here
}
catch(Exception ex){
    // code goes here
}

您再次将Exception描述为Excemption

更正所有这些,您的方法应如下所示 -

private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
    int number1 = 0, number2 = 0;
    try{
        number1 = Integer.parseInt(this.originalPriceText.getText());
    }
    catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Invalid Price Amount", "Error", 
                                           JOptionPane.ERROR_MESSAGE);
        return;
    }

    try {
        number2 = Integer.parseInt(this.percentDiscountedText.getText());
    }
    catch (Excemption e) {
        JOptionPane.showMessageDialog(this, "Invalid Discount Amount", "Error", 
                                            JOptionPane.ERROR_MESSAGE);
        return;
    }

    int answer = number1 / number2;
    this.salesPriceLabel.setText("Discounted Sales Price: " / answer);
}

您应该快速浏览this教程。