使用 Double.parseDouble() 进行 Java 文本框验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3516896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:12:04  来源:igfitidea点击:

Java Text Box Validation Using Double.parseDouble()

javavalidationdouble

提问by Carlo del Mundo

I have a Swing JTextBoxthat basically will hold a double.

我有一个JTextBox基本上可以容纳双人的 Swing 。

I find that using:

我发现使用:

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

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

每当Double.parseDouble()获得无效输入时都会抛出异常(因此程序终止)。

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

我的问题:有没有一种简单的方法可以不抛出异常,而是返回一个整数,(-1)说 parseDouble() 失败了?

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!

谢谢哈哈。我怎么能忘记捕捉异常呢?这是漫长的一天!

回答by jjnguy

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

处理此问题的最佳方法是使用 try/catch 块。

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

The JOptionPaneis a great way to display warning messages to users.

JOptionPane是向用户显示警告消息的好方法。

回答by James Van Huis

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

捕获NumberFormatException, 并返回所需的错误值(或从 catch 子句中执行一些其他操作)。

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

回答by Frank

Use

利用

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