Re: ArrayList -- cumulatively calculates??




"thickface" wrote...

> I have a question. I would appreciate it if anyone could help me out.
> I have made 3 array lists. And now i want to calculate the average of
> each array list. But my getAverage method calculate cumulatively, so
> when i print the list of heavy (or light) antlist then it works well.
> it only prints the number of ants in the heavy (or light ) antlists.
> But as for average weight, it calculates cumulatively, in other words,
> it calculates all the ants in the three lists. Does anyone know why it
> happens? Thank you in advance.


> public class Main {
> // define class variables
> public static int nextID = 0; // unique ID number for instances
> public static int numberOfAnts = 32, cnt = 0;; // answer 0
> public static double averageWeight = 0, sumWeight = 0;

You haven't reset the variables above between the calculations...

> public static void getAverage ( ArrayList <Ant> list ) {

// As you use them now, you should reset the variables you use
// in the calculation here, to 0...

// Besides, why do you calculate averageWeight *inside* the loop?
// ...and why use cnt at all, when you have list.size()?

> for ( int i = 0; i < list.size(); ++i ) {
> Ant a = list.get( i );
> sumWeight += a.getWeight();
> cnt = cnt + 1 ;
> averageWeight = sumWeight / cnt;
> }

// Bjorn A


.