Search code examples
javaoopjapplet

Find Exception caller and modify to display a value


Suppose I have 3 TextFields - used for users to input values into (when the program is running):

TextField input1 = new JTextField("00");
TextField input2 = new JTextField("00");
TextField input3 = new JTextField("00");

When the user inputs values, the program then takes those values and stores them as Integers (for operations later on):

public void actionPerformed(ActionEvent e) {

  String temp1 = input1.getText();
  String temp2 = input.getText();
  String temp3 = input3.getText();

  int num1=0, num2=0, num3=0;
  if(e.getSource() == storeButton){
      try{
          num1 = Integer.parseInt(tem1);
          num2 = Integer.parseInt(temp2);
          num3 = Integer.parseInt(temp3);
      } 
      catch(NumberFormatException ex){
          JOptionPane.showMessageDialog(null, "Input must be an integer from 0 to 50");
      }
  }
}

As the above code shows, when the user clicks the storeButton the values in the TextFields are parsed into the specific variables as integers and if any of the TextFields contain an input besides an integer, a message will pop up.

The question:

When the exception is called, how do I clear (set to "0") the TextField that does not contain a number? The TextFields that contain an integer must not be cleared. I can do that by using try and catch for each of the TextFields when parsing as integers but that would mean too much repetition of code (especially when there are many TextFields).


Solution

  • Take a look at Character.isDigit(). You could make a sub-method that loops through each String and checks it to see if it is a digit. Alternatively, you could use a regex on the String to check if it is a digit. This lets you get rid of the try/catch and handle them with if/else.