Shlok K
Shlok K

Reputation: 3

Java error checking for text field

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

Answers (3)

Fay007
Fay007

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

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

Jonah Haney
Jonah Haney

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

Related Questions