You're getting this because totalCost
is null, and then you're trying to use the object that it references.
What you should do is add this line to your class's constructor.
totalCost = BigDecimal.ZERO;
题
I can't get this to work. I have written notes that will hopefully explain what I'm attempting to do. The console outputs an error at the line 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
}
解决方案
You're getting this because totalCost
is null, and then you're trying to use the object that it references.
What you should do is add this line to your class's constructor.
totalCost = BigDecimal.ZERO;