尝试 - 捕获异常Java - Eclipse

时间:2014-08-08 23:02:46

标签: java try-catch

我想在程序中使用Execption在Java中使用这个try / catch。基本上,该计划旨在获得某个产品的数量/数量,并计算其价格和折扣。

我希望只有接收数字的txtAmount如果在这里放置字母是代码的一部分就不会崩溃。只是一个简单的解决方案

public static String modelo, obsequio = null, resolucion = null;
    public static int amount, numgift = 0, resolution = 0;
    public static double amountourchase = 0, idiscount = 0, itopayr = 0, discount = 0, price = 0;

    protected void actionPerformedBtnSell(ActionEvent arg0) {
        inData();
        calculateDiscount();
        prrocessPurchase();
        Results();
    }

    void indata(){
        model = cboModelo.getSelectedItem().toString();
        amount = Integer.parseInt(txtCantidad.getText());
    }

2 个答案:

答案 0 :(得分:1)

void indata() {
    model = cboModelo.getSelectedItem().toString();
    try {
        amount = Integer.parseInt(txtCantidad.getText());
    } catch (NumberFormatException e) {
        // Handle it here
    }
}

答案 1 :(得分:0)

代码:

try {
        double d = Double.parseDouble(your input is here);
         or
        int i =  Integer.parseInt(your input is here);
    }
    catch (NumberFormatException e) {
         System.out.print(e);

    }

注意:尝试解决这个问题我认为下面的代码是您正在寻找的代码。

代码:

public static void main(String[] args) {
        JFrame f = new JFrame("Demo");
        f.setLayout(new FlowLayout());
        f.setSize(300, 200);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);
        JLabel label = new JLabel("enter your number: ");
        JTextField userText = new JTextField(6);
        JButton button = new JButton("OK");
        JLabel label1 = new JLabel();

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                try {
                    int i = Integer.parseInt(userText.getText());
                    label1.setText(Integer.toString(i));
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(f,
                            "Input integer number ",
                            "NumberFormatException",
                            JOptionPane.ERROR_MESSAGE);
                    userText.setText("");
                }
            }
        });

        f.add(label);
        f.add(userText);
        f.add(button);
        f.add(label1);
        f.setVisible(true);
    }

注意:  你应该在double类型中定义你的金额和其他变量,以更精确