有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中将BigDecimal添加到BigDecimal

我没法让它工作。我写了一些笔记,希望能解释我正在尝试做什么。控制台在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) 个答案

  1. # 1 楼答案

    之所以会出现这种情况,是因为totalCost为空,然后您试图使用它引用的对象

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

    totalCost = BigDecimal.ZERO;