0

I want to calculate values from Java List. I managed to create the code using float in order to store money amount.

    private float sumAmounts(List<ExpressCheckout> myList)
    {
        float total = 0.0f;
        for (ExpressCheckout item : myList)
        {
            total += item.getAmount();
        }
        return total;
    }

I tried this code:

private BigDecimal sumAmounts(List<ExpressCheckout> myList)
{
    BigDecimal total = new BigDecimal(BigInteger.ZERO);
    for (ExpressCheckout item : myList)
    {
//            total += item.getAmount();
        total.add(item.getAmount());

    }
    return total;
}

But I get NPE when I execute the code. Is this a proper way to use BigDecimal?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • 1
    The NPE appears to have nothing to do with BigDecimal and all to do with your code throwing a NPE. Do you know how to debug NPE's? If not, search for the canonical question/answer on this, and debug your program first. – Hovercraft Full Of Eels Oct 22 '16 at 20:59
  • 1
    Either `myList` or one of the `item`s is `null`. What line produces the NPE? – Mureinik Oct 22 '16 at 20:59
  • NPE link: http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – Hovercraft Full Of Eels Oct 22 '16 at 21:00
  • Where do you get the NPE? – Brunaldo Oct 22 '16 at 21:01
  • FWIW, it should be `total = total.add(item.getAmount());`, assuming this `getAmount()` returns a *BigDecimal*. *BigDecimals* are immutable, so add returns a *new* instance of *BigDecimal*. This must be assigned to. I doubt this causes your NPE, though. – Rudy Velthuis Oct 23 '16 at 10:57

0 Answers0