3

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.

1
  • 1
    For future reference, your problem is solved by reading the Javadoc. Commented Nov 5, 2012 at 11:25

3 Answers 3

5

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

sum = sum.add(heights[a]);
Sign up to request clarification or add additional context in comments.

1 Comment

The ole immutable value class problem... Yup, it's a trap for new players, and we programmers are all new players... constantly to start with, and occasionally as we gain experience. Sigh.
4

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

Comments

1

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));
    }        

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.