2013-11-21 36 views
0
NumberFormat numForm = NumberFormat.getCurrencyInstance(); 
    double itemPrice; 
    String s = (String)JOptionPane.showInputDialog("Enter item price:"); 
    if (s.equals("") || s == null) { 


    } else { 
     try{ 

      itemPrice = Double.parseDouble (s); 
      recordPurchase(itemPrice); 
      txtPrice.setText(numForm.format(itemPrice)); 

      double subtotal = getPurchase();  

      txtSubtotal.setText(numForm.format(subtotal)); 
      int items = getItems(); 
      String totalItems = Integer.toString(items); 
      txtItems.setText(totalItems); 

     } // end try 
     catch (NumberFormatException e) { 
      JOptionPane.showMessageDialog(this, "You must enter positive numeric data!"); 
     } // end catch 
    } // end if Else 

我目前工作的一个program.My问题是if语句,我检查,看看用户点击还好没事在框中或者选择取消。仅当单击取消时才会出现NullPointerException错误。如果任何人可以澄清为什么发生这种情况,将不胜感激。取消按钮showDialogInput发出

回答

1

发生这种情况是因为当用户单击取消时,返回值为空。我看到你试图通过添加测试s == null来解决这个问题,但那是错误的地方。您的if语句应该是:

if (s == null || s.equals("")) {