0

I have two text fields and they must add up to 100 when submit is clicked, if I put in correct values into text field there's no error but if I leave the text field blank or put a letter in it the error handling isn't right. Any ideas?

submit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        if (validation == true) {
            int numA = Integer.parseInt(aTextField.getText());
            int numB = Integer.parseInt(aTextField.getText());
            int sum = numA + numB;

            if (sum == 100) {
                validation = true;
                System.out.println("success");
            } else {
                JOptionPane.showMessageDialog(createFrame, "A and B must add up to 100");
                validation = false;

            }


        }

this is the error

int numA = Integer.parseInt(aTextField.getText());
  • You must check the values before converting it. Or use something like that http://stackoverflow.com/questions/14319064/how-to-validate-a-jtextfield-to-accept-only-interger-numbers – pL4Gu33 Apr 30 '14 at 16:35

2 Answers2

1

Integer.parseInt(str); throws a NumberFormatException (the error you are seeing) if the String parsed into the method can not be converted into a number.

You could use some exception handling in this particular situation. I would suggest a try and catch block. For example;

   try{
       if(validation == true){
            int numA = Integer.parseInt(aTextField.getText());
            int numB = Integer.parseInt(aTextField.getText());
            int sum = numA + numB;

            if(sum == 100){
                validation = true;
                System.out.println("success");
            } else{
                JOptionPane.showMessageDialog(createFrame, "A and B must add up to 100");
                validation = false;
            }
        }
    } catch (NumberFormatException n){
            JOptionPane.showMessageDialog(createFrame, "Only numbers should be entered into A and B");
            validation = false;
    }

If the exception is now thrown from within the try block, it will be 'caught' and then validation will be set to false in the catch block. You could also use the catch block to display a message saying that only numbers should be entered into the fields.

Another way to achieve this using the Swing API is if you don't want them to ever put texts into those fields you could use a JFormattedTextField to allow them to only enter numbers.

I hope this helps. Let me know how you get on.

Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77
0

Check the javadoc of Integer.parseInt! The function cannot handle an empty string. What number should that be anyways?

Possible solutions:

  • set the default text of your textFields to "0"

  • add exception handling for the parseInt calls (you could fall back to 0 or prompt the user to correct)

SebastianH
  • 2,172
  • 1
  • 18
  • 29