cworner1
cworner1

Reputation: 451

Java: Simple BigDecimal logical error

I've got a simple piece of code that isn't behaving as it should.

This piece of code is attempting to add an array of BigDecimals to then divide by array.length to find an average. However, the first phase of the algorithm fails to add the arrays together correctly (in the variable "sum").

public BigDecimal getAverageHeight()
{
    BigDecimal sum = new BigDecimal(0);
    BigDecimal[] heights = getAllHeights();

    for (int a = 0; a < heights.length; a++)
    {
        sum.add(heights[a]);
        System.out.println("Height[" + a + "] = " + heights[a]);
        System.out.println("Sum = " + sum.setScale(2, BigDecimal.ROUND_HALF_UP));
    }        

    return sum.divide(new BigDecimal(heights.length));
}

The output is as follows:

Height[0] = 24  
Sum = 0.00  
Height[1] = 24  
Sum = 0.00  
Height[2] = 24  
Sum = 0.00  
Height[3] = 26  
Sum = 0.00  
Height[4] = 26  
Sum = 0.00  
Height[5] = 26  
Sum = 0.00

I'm sure its a simple error, but I'm getting tired of starring at the problem, thanks in advance.

Upvotes: 3

Views: 220

Answers (3)

Frank
Frank

Reputation: 15631

BigDecimal object are immutable, all its methods modifying its value return a new BigDecimal object. The newly created object contains the value modified.

You need to do something like this:

sum = sum.add(heights[a]);

This also goes for the setScale() and divide() operations

Upvotes: 4

Ahmad
Ahmad

Reputation: 12707

Assign the result value of the addition operation of sum back to the variable sum

for (int a = 0; a < heights.length; a++)
    {
        sum = sum + heights[a];
        System.out.println("Height[" + a + "] = " + heights[a]);
        System.out.println("Sum = " + sum.setScale(2, BigDecimal.ROUND_HALF_UP));
    }        

Upvotes: 1

user647772
user647772

Reputation:

BigDecial.add() returns the sum, it does not alter it. Do this:

sum = sum.add(heights[a]);

Upvotes: 5

Related Questions