如何将BigDecimal作为类变量求和

时间:2017-03-06 13:19:54

标签: java nullpointerexception bigdecimal

我有这堂课:

Builing

我在Main上测试了这个:

public class Period {
private BigDecimal periodAmount;

public BigDecimal getPeriodAmount() {
    return periodAmount;
}

public void setPeriodAmount(BigDecimal periodAmount) {
    this.periodAmount = periodAmount;
}

但它抛出了一个我无法找到原因的NullPointerException。我试过没有列表,像这样:

public static void main(String[] args){
    BigDecimal total = new BigDecimal(0);
    List<Period> periods = new ArrayList<Period>();

    Period periodOne = new Period();
    Period periodTwo = new Period();
    Period periodThree = new Period();
    Period periodFour = new Period();
    periodOne.setPeriodAmount(new BigDecimal(33564899.47));
    periodTwo.setPeriodAmount(new BigDecimal(22978517.87));
    periodThree.setPeriodAmount(new BigDecimal(19526899.32));
    periodOne.setPeriodAmount(new BigDecimal(18056899.98));

    periods.add(periodOne);
    periods.add(periodTwo);
    periods.add(periodThree);
    periods.add(periodFour);

    for(Period b : periods){
        total.add(b.getPeriodAmount());
    }
    System.out.println(total);
}

然后我将总数打印为0.我做错了什么?

0 个答案:

没有答案