Reputation: 25
I'm trying to calculate the average of an array for only the values that aren't 0. My array is of size 15, because it could have up to 15 values in it.
When I calculate the average, it uses all 15 values, even though 12 of them are 0 at the start. How do I prevent 0.0’s from being considered?
for(double element: majorA) {
Sum += element;
}
average = sum / majorA.length;
System.out.printf("%.5f\n", average);
The array also isn't a defined set, but dependent on what the user inputs. The initial array is:
double[] majorA = new double[15];
Then gets values as need:
majorA[0] = num1;
majorA[1] = num2;
...
Upvotes: 1
Views: 74
Reputation: 109
You can do it in one line with
Arrays.stream(majorA).filter(d -> d != 0).average().orElse(0)
this will filter out all values that are 0s and will calculate the average. Even if there is nothing left in the array will display 0 because of .orElse(0)
Upvotes: 1
Reputation: 1506
you can use a counter in the loop that increments only if the number !=0
int count = 0;
for(double element: majorA) {
if(element != 0.0){
sum += element;
count++;
}
}
average = (count == 0) ? 0 : sum / count;
Upvotes: 0
Reputation: 358
I would just add a counter that keeps track and use that instead of the array length.
int count = 0;
for(double element: majorA) {
if(element > 0.0) {
Sum += element;
count += 1;
}
}
average = sum / count;
System.out.printf("%.5f\n", average);
Upvotes: 2