简体   繁体   中英

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!

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.

Catch the NumberFormatException , and return your desired error value (or take some other action from within the catch clause).

double value = -1;
try {
    value =  Double.parseDouble(this.myTB.getText());
} catch (NumberFormatException e) {
    e.printStackTrace();
}
return value;

Use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM