2014-02-17 77 views
-1

我無法使其工作。我已經寫了筆記,希望能夠解釋我正在嘗試做什麼。控制檯在該行totalCost = totalCost.add(new BigDecimal(result));在Java中向BigDecimal添加BigDecimal

private void btn_motherboardActionPerformed(java.awt.event.ActionEvent evt) {             

    String cost = cb_motherboard.getSelectedItem().toString(); 
    //gets item from combobox. Makes a string 
    Components.addElement(cost);// adds string to model 
    lb_computer_components.setModel(Components);//sets model to jlist 

    String result = cost.substring(cost.lastIndexOf('£') + 1); 
    //creates a substring containing information after £ (for example 45.99) 

    totalCost = totalCost.add(new BigDecimal(result)); 
    //totalcost is a public bigdecimal, i want to add 45.99 to it in this example 

    String BD = totalCost.toString(); 
    //change the new totalcost to a string 

    String stringTotal = n.format(BD); 
    //format that string to a currency 

    txt_total_computer.setText(stringTotal); 
    //output that string to a textfield 

}   
+0

您是否嘗試過使用打印來查看varible的值以查看其失敗的位置? – user2097804

+5

什麼是錯誤? – Radiodef

+0

哦,對不起,它開始像這樣線程「AWT-EventQueue-0」中的異常java.lang.NullPointerException \t at computer.INTERface.btn_motherboardActionPerformed(INterface.java:2324) – user3320339

回答

0

你得到這一點,因爲totalCost是空輸出錯誤,然後你想使用的對象,它的引用。

你應該做的是將這一行添加到你的類的構造函數。

totalCost = BigDecimal.ZERO; 
+0

謝謝。我沒有意識到如何初始化bigdecimal的全局變量版本。我希望我的基本問題不是太煩人。 – user3320339