In the method below trying to calculate average age in each category('o','u','n'). Ages are stored in a separate class.

Code:

``````public double averageAge() // calculating average age in each BMI group
{
double numbers[]=new double[this.list.length];
double result=0;
char[] cat={'O','U','N'};
for (int i=0;i<this.list.length;i++){
int b=this.list[i].age;
for(int j=0;j<3;j++){//loop runs three times, as there are three categories
if(b==cat[0]){
result=result+b;
numbers[j]++;}
}
}       for (int j=0;j<3;j++)
System.out.println("Average age in group "+cat[j]+ " is "+result/this.list.length);
return result;
}
``````

Result returns 0.. Any ideas how this can be fixed?

Edited by mike_2000_17: Fixed formatting

2
Contributors
1
2
Views
6 Years
Discussion Span
Last Post by thekashyap
``````public double averageAge() // calculating average age in each BMI group
{
double numbers[] = new double[this.list.length];
// KASH: You probably need an array to store
// totals as well. One total per "cat".
double result = 0;
char[] cat = {'O', 'U', 'N'};

for (int i = 0;i < this.list.length;i++) {
int b = this.list[i].age;
for (int j = 0;j < 3;j++) {//loop runs three times, as there are three categories
// KASH: should index into cat using loop var "j"
if (b == cat[0]) {
// KASH: SHould be "result[j] += b;"
result = result + b;
numbers[j]++;
}
}
}

for (int j = 0;j < 3;j++)
System.out.println ("Average age in group " + cat[j] + " is " + result / this.list.length);

return result;
}``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.