Reputation: 3
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);
}
Upvotes: 0
Views: 1515
Reputation: 2917
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
Upvotes: 0
Reputation: 48258
use regex
String regex = "\\d+";
and then
System.out.println(myString.matches(regex));
Your final snippet can look like
fieldID.getText().matches(regex));
Upvotes: 1
Reputation: 521
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.
Upvotes: 0