[英]Java Text Box Validation Using Double.parseDouble()
I have a Swing JTextBox
that basically will hold a double. 我有一个Swing JTextBox
,基本上会持有一个双。
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! 这是漫长的一天!
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 JOptionPane
is a great way to display warning messages to users. JOptionPane
是向用户显示警告消息的好方法。
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;
Use 采用
try{
return Double.parseDouble(this.myTB.getText());
} catch(NumberFormatException e) {
return -1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.