1

这是我的一个简短示例代码的问题:

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

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

请任何建议我如何解决这个问题?

提前致谢

4

2 回答 2

4

首先,您需要验证输入是否为空。如果没有,那么你使用 parseDouble 就可以了。

像这样:

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

此外,尽量不要像您所做的那样通过放置“异常”来捕获异常。始终尝试尽可能多地指定您正在寻找的异常。在这种情况下,您应该使用 NumberFormatException 而不仅仅是 Exception。

catch (NumberFormatException e)
{
    System.err.println("Error: Invalid Input!");
    JOptionPane.showMessageDialog(null, "Error: Invalid Input!",  
    "Error", JOptionPane.ERROR_MESSAGE);
}
于 2011-01-05T19:15:59.693 回答
1
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");
        }


    }
}
于 2011-01-05T19:06:35.363 回答