【发布时间】:2012-02-23 10:23:03
【问题描述】:
我有一个用作计算器的 GUI。当我输入除数字以外的任何内容时,它会按预期抛出 NumberFormatException。但是当我输入诸如“23423f”之类的数字时,程序似乎认为我正在输入一个浮点数并且不会抛出异常,因为最后是 f,即使所有其他字母都会抛出异常。
目前,我所做的只是将输入部分放入一个 try catch 块中,在那里我将其解析为双精度数,并让它捕获一个 NumberFormatException 如果有一个(因为只有数字可以解析成双精度数),和另一个 catch 块,用于从 if 语句中为任何小于 0 的输入抛出 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);
}
【问题讨论】:
-
并非所有其他字母,'d' 表示双精度,以及 'e' 表示指数,如 '1.2e+3'
标签: try-catch