在Java中将BigDecimal添加到BigDecimal

时间:2014-02-17 18:24:39

标签: java bigdecimal addition

我无法让这个工作。我写了笔记,希望能够解释我正在尝试做什么。控制台在行totalCost = totalCost.add(new BigDecimal(result));

处输出错误
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

}        

1 个答案:

答案 0 :(得分:0)

你得到这个是因为totalCost为空,然后你试图使用它引用的对象。

你应该做的是将这一行添加到你的类的构造函数中。

totalCost = BigDecimal.ZERO;