如何在Java(JOptionPane.showInputDialog)中的(“ Cancel”)按钮上分配单独的动作? [英] How to assign a sepecifc action to the ("Cancel") button within (JOptionPane.showInputDialog) in Java?

查看:247
本文介绍了如何在Java(JOptionPane.showInputDialog)中的(“ Cancel”)按钮上分配单独的动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题,带有简短的示例代码:

Here is my question with a short sample code:

 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");
}

*上面代码的问题是,当我单击取消时按钮,程序同时遇到两个错误:(超出范围和无效输入)。

*The Problem with the above code is that when i click the "cancel" button, the program is hitting both errors: (the out of range and the invalid input).

请问我如何解决此问题的任何建议?

Please any suggestions how i can fix this?

预先感谢

推荐答案

首先,您需要验证输入为空。如果不是,则对它使用parseDouble。

First, you need to verify if the input is null. If not, then you use parseDouble on it.

像这样:

try
{
    String i = JOptionPane.showInputDialog("Enter your num:");
    if (i != null)
        num = Double.parseDouble(i);
}

另外,请像您一样尝试通过放置 Exception来捕获异常。始终尽量指定您要查找的异常。
在这种情况下,您应该使用NumberFormatException而不是Exception。

Also, try to not catch exceptions by putting "Exception", like you did. Always try to specify the exception you are looking for as much as possible. In this case, you should use NumberFormatException instead of just Exception.

catch (NumberFormatException e)
{
    System.err.println("Error: Invalid Input!");
    JOptionPane.showMessageDialog(null, "Error: Invalid Input!",  
    "Error", JOptionPane.ERROR_MESSAGE);
}

这篇关于如何在Java(JOptionPane.showInputDialog)中的(“ Cancel”)按钮上分配单独的动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆