Question

I'm trying to get the user to input an integer into the textfield. The try catch block should handle the exception when the user enters a non-integer. A message dialog should appear, telling the user that they should input something else but I can't seem to get it to do so.

    class ButtonListener implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {
            try
            {
                String r = radiusField.getText ();
                int radius = Integer.parseInt (r);
                double area = Math.PI * radius * radius;
                areaArea.setText ("" + area);
            }

            catch (InputMismatchException ex)
            {
                JOptionPane.showMessageDialog (null, "Error in number format: Reenter the number");
                radiusField.setText ("");
                areaArea.setText ("");
            }
        }
    }
Was it helpful?

Solution

Use NumberFormatException instead of InputMismatchException:

catch (NumberFormatException ex) {
  /* ... */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top