Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# finding an average

Mike Smith
Ranch Hand
Posts: 85
Hello, good day all. I had a question about getting an average value from an
array[]. I have the following piece of code below, for reference.

My goal is to sum the values in an array, then divide them but the count variable to find out the average of the values.
Okay, I have figured that the problem lies within the sum variable. Since
the application only seems to be giving the average number of the last value
in the array. How do I allow for the suming of values in different elements
within the array. That is how do I add the values within the array to yield
the sum, and assign those summed values to the sum variable. My counter is
working fine, only the sum variable is not summing all of the requested
values. I see sum+=scores[i]; as the following sum= scores[0] + scores[1];
Please correct me if I am using the += operator incorrectly. Thanks again.

[ EFH: Added code tags. Mike, you can edit your own messages. ]
[ January 21, 2006: Message edited by: Ernest Friedman-Hill ]

Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791

Check out the "-1" in the for loop. Would that explain why you don't seem to add in all the elements in the array?

Your count variable is the number of elements in the array. You already have another expression in your code that is the number of elements in the array. Do you see it? Maybe you could do without count.

Let us know if those ideas help. Keep having fun, keep asking questions!

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24211
35
There are three things wrong here, two of which could be causing you to get erroneous results. One is that to visit every element of an array, the upper limit of your "for" loop should be "scores.length", not "scores.length-1". As it stands, you're leaving off the last item in the array.

The other is that when findAverage() is called, "sum" and "count" might not both be zero -- you may have called this routine already -- so the computed value may be wrong. Rather than being member variables, as here, they should be local variables, declared in the method itself, and initialized to zero right there:

int sum = 0;
int count = 0;

Now, finally, an exercise for you: can you describe for me a situation in which the value of "count" is ever different from "scores.length"? Of course, it never will. There's no need to count the elements of the array -- you already know how many there are, so just get rid of "count" altogether, and just use "scores.length."

Mike Smith
Ranch Hand
Posts: 85
Thanks guys for the input; it is greatly appreciated. I have the program all most running. However, I am trying to figure out how to use the methods of class DecimalFormat to be able to round my average variable up. I believe if I can get that part to work then the average should be reading correctly.

Mike Smith
Ranch Hand
Posts: 85
Hi again. Okay I read up some more on the topic of Class DecimalFormat, and it seems that this class is only used to format numbers before printing them out. So my question is how do I round up? to say 2 decimal places. I have read about java.util.Math.BigNumber and just java.util.Math class. I have searched for examples on how to round up, but haven't found anything close for which I am searching for. My text does not explain it well either; in any specific detail. Damn Problem Solving with Java. Oh well. If anyone could give me some suggestions that would be great. Thanks again.

Chengwei Lee
Ranch Hand
Posts: 884
You're right in that DecimalFormat class merely helps you format the number into the desired format (including your rounding off to 2 decimal places).

There's a class that would fit your needs, java.math.BigDecimal. Read up its API & you should be able to solve your problem.

Mike Smith
Ranch Hand
Posts: 85
Hello there, okay I confused on using DecimalFormat class. I tried to instantiated a new object from this class however, it reads the same thing as before. For example, I declare and initialize value in the private fields section of my code.That is, right at the beginning of my Student worker class.

Next, I do the following;

all I want to be able to accomplish here is for example I enter the following;
mike 10 10 9.5 9.5
The answer I want is 9.75 not the 9.5 it reads to the screen.

Student's Name: mike
The average of the test mark scores is 9.5

Garrett Rowe
Ranch Hand
Posts: 1296
Part of the problem that I see is that you when you count the number of scores, you are cutting off the last one.
int numberOfScores = scores.length;

if you have an array with ten scores, although the indices range from 0-9, there are still 10 values. You can avoid this alltogether by using the for-each idiom.

Also I don't think you are using the BigDecimal class correctly.

Unfortunately, I'm at school so I can't test this method, but it looks right to me .
[ January 23, 2006: Message edited by: Garrett Rowe ]

Mike Smith
Ranch Hand
Posts: 85
Hi there, I tried the BigDecimal Format;just as you did in your code. I now get the following for entering this input.

mike 10 10 9.5 9.5

output

Student's Name: mike
The average of the test mark scores is 8

It seems like the precision has decreased. Before I got 9.5

Layne Lund
Ranch Hand
Posts: 3061
I think BigDecimal is overkill here. There is a Math.round() method that might server your purposes better.

Layne

James Wardjr
Greenhorn
Posts: 2
The following code will give you the 9.75 answer that you are looking for.

double scoreTotal = 0.0;
int scoreCount = 0;
double testScore = 0.0;
double minScore = 999;
double maxScore = 0;

Scanner sc = new Scanner(System.in);

while (testScore < 999)
{
System.out.print("Enter score: ");
testScore = sc.nextDouble();

if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
minScore = Math.min(minScore, testScore);
maxScore = Math.max(maxScore, testScore);
} else if (testScore > 100 && testScore < 999)
{
System.out.println();
System.out.println("Invalid entry, not counted in scoring...");
}
}

double averageScore = scoreTotal / (double)scoreCount;
BigDecimal bdScoreTotal = new BigDecimal(Double.toString(scoreTotal));
BigInteger bdScoreCount = new BigInteger(Integer.toString(scoreCount));
BigDecimal bdAvgScore = new BigDecimal(averageScore);
bdAvgScore.setScale(1, RoundingMode.HALF_UP);

Campbell Ritchie
Sheriff
Posts: 48968
60
Welcome to the Ranch
Nice to see you using BigDecimal, but are you sure they still want the answer after 7 years?

Campbell Ritchie
Sheriff
Posts: 48968
60
Never use doubles as parameters to the BigDecimal class. that may perpetuate the imprecision of double. Read BigDecimals directly with the appropriate method of the Scanner class.

James Wardjr
Greenhorn
Posts: 2
I understand that after seven days the original request may not be needed but the answer to the question was not complete. I post the answer for anyone later that may be looking.