线程“AWT-EventQueue-0”中的异常java.lang.NumberFormatException:为空

时间:2017-11-20 15:26:27

标签: java swing

谁能帮帮我?我在Netbeans中得到了这个例外

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

谁能告诉我如何修复它?谢谢

2 个答案:

答案 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();
    }
}