0

I need to check whether a text field (ID) has anything other than a numerical value. I am parsing the string in the text field to a int. I tried catching the error with a try-catch block, but every time the field has anything other than an int, it displays an error messages and terminates the whole program. I want the user to be able to go back and edit the ID field.

try{
    int id = Integer.parseInt(fieldID.getText());
}
catch(NumberFormatException e2){
    JOptionPane.showMessageDialog(null, "Please enter a valid ID","Alert!", JOptionPane.ERROR_MESSAGE);
} 
Shlok K
  • 3
  • 6
  • Can you share some more code? – shmosel Feb 23 '16 at 04:51
  • Consider using a `JSpinner` or `JFormattedTextField` or if you're really desperate a `DocumentFilter`, this will allow you to restrict what the OP can enter – MadProgrammer Feb 23 '16 at 04:52
  • Please use some `regex` Validation against the `fieldID.getText()` . and if it contains only numeric then only go for parsing. otherwise it may cause the `Exception` – Vikrant Kashyap Feb 23 '16 at 04:52
  • Already answered here - [How to check if a String is numeric in Java](http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java) – ThisClark Feb 23 '16 at 04:52

3 Answers3

1

use regex

String regex = "\\d+"; 

and then

System.out.println(myString.matches(regex));

Your final snippet can look like

fieldID.getText().matches(regex));
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Try changing the catch statement to just catch any exception regardless of type

catch (Exception e2){

It would be helpful to see your error's stack trace.

Jonah Haney
  • 521
  • 3
  • 12
  • When I change it to 'Exception', I'm getting the same error: `java.lang.NumberFormatException:For input string: "a"`, if I type the letter 'a' in the ID field. – Shlok K Feb 23 '16 at 10:24
  • @ShlokK Is the error being thrown later in the code? If the Message Dialog shows up, then the exception IS being processed correctly. You may want to set a `boolean invalid` to true within your exception catching, and then later in the program do something like `if (!invalid)` so that it will know if `id` has a valid value. – Jonah Haney Feb 23 '16 at 18:00
  • Yes the message dialog does come up, but then the program just crashes. I have implemented JFormattedTextFields now, but I think I can use this boolean to display a message after the entered text is invalid. Thanks! – Shlok K Feb 25 '16 at 03:31
0

Why don't u restrict the input field for numeric number only!! then u won't have such botheration to try catch it. Checkout this answer: https://stackoverflow.com/a/8017847/2356808

Community
  • 1
  • 1
Fay007
  • 2,707
  • 3
  • 28
  • 58