开发者

Java Text Box Validation Using Double.parseDouble()

开发者 https://www.devze.com 2023-01-12 08:33 出处:网络
I have a Swing JTextBox that basically will hold a double. I find that using: Double.parseDouble(this.myTB.getText());

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()开发者_如何学JAVA 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;
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消