-2

I have this program in which I need to add up many BigDecimals. I have the following snippet of code

BigDecimal Average = new BigDecimal(3.0);
BigDecimal ATT = new BigDecimal(0.0);
ATT.add(A_BigDecimal);
ATT.add(B_BigDecimal);
ATT.add(C_FullBigDecimal);
System.out.println("Total Amount: " + ATT); 
System.out.println("Average: " + ATT.divide(Average));

I keep getting errors everytime I try variants of this code, how do you add many BigDecimals together? Edit: Forgot to mention that the output is zero, always zero, as if the reference variable isnt reading the add function.

Dcdw51
  • 15
  • 1
  • 8
  • What errors do you get? – Steve Oct 30 '16 at 20:56
  • @Steve for some reason the output is zero, I am really stuck – Dcdw51 Oct 30 '16 at 21:01
  • You should provide a reproducible example. `A_BigDecimal`, `B_BigDecimal` and `C_FullBigDecimal` are used but not defined anywhere. – Steve Oct 30 '16 at 21:09
  • Did you *read* the javadoc of [`add(BigDecimal augend)`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#add-java.math.BigDecimal-)? ***Returns** a BigDecimal whose value is (this + augend)* Or the javadoc of [`BigDecimal`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) itself? ***Immutable**, arbitrary-precision signed decimal numbers.* – Andreas Oct 30 '16 at 21:53

2 Answers2

3

BigDecimal is immutable. Once the object is created, it cannot be changed.

The add method will return the result of the calculation. You will probably want to assign that return value to something.

Joe C
  • 15,324
  • 8
  • 38
  • 50
1

This is what Joe C meant in updated code:

BigDecimal Average = new BigDecimal(3.0);
BigDecimal ATT = new BigDecimal(0.0);
ATT = ATT.add(A_BigDecimal);
ATT = ATT.add(B_BigDecimal);
ATT = ATT.add(C_FullBigDecimal);
System.out.println("Total Amount: " + ATT); 
System.out.println("Average: " + ATT.divide(Average));
whitebrow
  • 2,015
  • 21
  • 24