axisrod09
axisrod09

Reputation: 3

Try - Catch Exception Java - Eclipse

Well I want to use this try/catch in Java using the Execption in a program. Basically the program is aim to get the number/ amount of a certain product and it calculates its price and discount.

I want the txtAmount which is supposed to receive only numbers does not crash if put letters here is part of the code. Just a simple solution

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

Upvotes: 0

Views: 4457

Answers (2)

Kick Buttowski
Kick Buttowski

Reputation: 6739

Code:

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

    }

Note: try to work on this I think the code in below is the one that you are looking for.

Code:

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

Note : you should define your amount and other variables in type double to be more precise

Upvotes: 0

Dan Dosch
Dan Dosch

Reputation: 321

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

Upvotes: 1

Related Questions