如何分配(JOptionPane.showInputDialog)在Java中内的具体行动,对(“取消”)按钮?
-
25-09-2019 - |
题
下面是我的问题用短代码示例:
double num = 0.00;
try
{
num = Double.parseDouble(JOptionPane.showInputDialog("Enter your num:"));
}
catch (Exception e)
{
System.err.println("Error: Invalid Input!");
JOptionPane.showMessageDialog(null, "Error: Invalid Input!",
"Error", JOptionPane.ERROR_MESSAGE);
}
//Validate the num
if (num > 0.0 && num <= 1000.00)
{
functionA();
}
else if (deposit <= 0.0 || deposit > 1000.00)
{
System.err.println("Error: out of range");
}
*存在的问题与上述代码是,当我点击“取消”按钮时,程序被击中这两个错误:(超出范围和无效输入)
请任何建议,我怎么能解决这个问题?
在预先感谢
解决方案
首先,你需要验证,如果输入为空。如果没有,那么你用parseDouble就可以了。
像这样:
try
{
String i = JOptionPane.showInputDialog("Enter your num:");
if (i != null)
num = Double.parseDouble(i);
}
另外,尽量不要通过将“异常”,像你这样捕获的异常。总是试图指定要尽可能寻找例外。 在这种情况下,你应该使用NumberFormatException的,而不只是例外。
catch (NumberFormatException e)
{
System.err.println("Error: Invalid Input!");
JOptionPane.showMessageDialog(null, "Error: Invalid Input!",
"Error", JOptionPane.ERROR_MESSAGE);
}
其他提示
package org.life.java.so.questions;
import java.text.ParseException;
import javax.swing.JOptionPane;
/**
*
* @author Jigar
*/
public class InputDialog {
public static void main(String[] args) throws ParseException {
String input = JOptionPane.showInputDialog("Enter Input:");
if(input == null){
System.out.println("Calcel presed");
}else{
System.out.println("OK presed");
}
}
}
不隶属于 StackOverflow