输入时如何使浮动抛出异常?

时间:2012-02-23 02:12:43

标签: try-catch

我有一个用作计算器的GUI。当我输入除数字以外的任何内容时,它会按预期抛出NumberFormatException。但是当我输入一个像“23423f”这样的数字时,程序似乎认为我正在进入一个浮点并且不会抛出异常,因为最后的f,即使所有其他字母都抛出异常。

目前,我正在做的就是将输入部分放入try catch块,在那里我将其解析为double,并且如果有的话,它会捕获NumberFormatException(因为只有数字可以解析成双精度数),和另一个catch块,用于从任何小于0的输入的if语句中抛出IllegalArgumentException。

这只是一个猜测,但我不知道为什么只有f最后不会抛出异常。

        try
        {
        // get the total sales. the input is a string
           stringInput = salesInputField.getText();
                double validAmount = Double.parseDouble(stringInput);
                if (validAmount < 0)
                    throw new IllegalArgumentException();

        // calculate the sales and county tax
           stateTaxes = validAmount * STATE_TAX;
           countyTaxes = validAmount * COUNTY_TAX;

        // display a message dialog showing the miles
           JOptionPane.showMessageDialog(null, "State Sales Tax: " + percent.format(stateTaxes) + "\n" +
                                                "County Sales Tax: " + percent.format(countyTaxes) + "\n",
                                                "Taxes Owed",
                                                JOptionPane.PLAIN_MESSAGE);
        }
           catch (NumberFormatException error)
           {
              JOptionPane.showMessageDialog(null, "Invalid Amount", "Input Error", JOptionPane.ERROR_MESSAGE);
           }
                catch (IllegalArgumentException error)
           {
              JOptionPane.showMessageDialog(null, "Invalid Amount", "Input Error", JOptionPane.ERROR_MESSAGE);
           }

1 个答案:

答案 0 :(得分:1)

听起来你的理论可能是正确的,因为你描述的输入是一个有效的浮点数/双数,所以你希望能够解析它。

明显的解决方案是检查字符串是否只包含您认为有效的字符(可能类似于dddd.dd)。

一般评论:将货币价值存储为整数,否则最终可能会出现可怕的四舍五入的事情。不要相信我的话,只是谷歌吧。

相关问题