2013-11-21 31 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("")) {