Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Text Box Validation Using Double.parseDouble()

I have a Swing JTextBox that basically will hold a double.

I find that using:

  Double.parseDouble(this.myTB.getText());

will throw an exception (and thus program is terminated) whenever Double.parseDouble() gets invalid input.

My question: is there an easy way to NOT throw an exception, and instead return an integer (-1) saying that parseDouble() failed?

I am trying to make a popup for the user saying he or she's data field is invalid.

Thanks


EDIT:

Thanks lol. How could I forget about catching exceptions? it's been a long day!


1 Answers

The best way to handle this is by using a try/catch block.

try {
    return Double.parseDouble(this.myTB.getText());
} catch (NumberFormatException e) {
    JOptionPane.showMessageDialog("Oops");
    return -1;
}

The JOptionPane is a great way to display warning messages to users.

like image 187
jjnguy Avatar answered Apr 21 '26 17:04

jjnguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!