簡體   English   中英

嘗試-捕獲Java異常-Eclipse

[英]Try - Catch Exception Java - Eclipse

我想在程序中使用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());
    }
void indata() {
    model = cboModelo.getSelectedItem().toString();
    try {
        amount = Integer.parseInt(txtCantidad.getText());
    } catch (NumberFormatException e) {
        // Handle it here
    }
}

碼:

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類型中定義您的金額和其他變量,以便更加精確

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM