Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException:
empty
String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
这是我的代码的一部分,可能会例外:
private void pizzaMouseClicked(java.awt.event.MouseEvent evt) {
double cMeal = Double.parseDouble(costmeal.getText());
double qPizza = Double.parseDouble(qtypizza.getText());
double cPizaa = 6000;
if(pizza.isSelected())
{
i[0] = (qPizza * cPizaa) + cMeal;
String pMeal = String.format("%.2f", i[0]);
costmeal.setText(pMeal);
}
}
谁能告诉我如何修复它?谢谢
答案 0 :(得分:0)
你必须检查costmeal.getText()和qtypizza.getText()都包含一个有效的数字,似乎其中一个是基于快照代码和堆栈跟踪的空。
答案 1 :(得分:0)
NumberFormatException是一个异常,当您尝试将String转换为数字(int,double,float等)时,可能会抛出该异常。您必须通过将代码放在try catch中或将异常添加到方法签名来处理异常。
private void pizzaMouseClicked(java.awt.event.MouseEvent evt) throws NumberFormatException {
double cMeal = Double.parseDouble(costmeal.getText());
double qPizza = Double.parseDouble(qtypizza.getText());
double cPizaa = 6000;
if(pizza.isSelected())
{
i[0] = (qPizza * cPizaa) + cMeal;
String pMeal = String.format("%.2f", i[0]);
costmeal.setText(pMeal);
}
}
或者
private void pizzaMouseClicked(java.awt.event.MouseEvent evt) {
try{
double cMeal = Double.parseDouble(costmeal.getText());
double qPizza = Double.parseDouble(qtypizza.getText());
double cPizaa = 6000;
if(pizza.isSelected())
{
i[0] = (qPizza * cPizaa) + cMeal;
String pMeal = String.format("%.2f", i[0]);
costmeal.setText(pMeal);
}
}
catch(NumberFormatException e){
e.printStackTrace();
}
}