Reputation: 19
I am trying to calculate and return the average of an array of integer values. The problem is, the array I am calculating the average from has values I need to find the average of, and values I need to exclude.
For example, take this as being my data set in the array. 20, -999, -10, 50, -999, 40, 30
I need to find the average but exclude any -999 value from the calculation.
How can I go about removing the -999 value from my sums and then find the new value to divide by at the end? Is there a way to keep count of the values I exclude? How can I exclude a value and move on to the next?
public static double averageTemperature(int[] temperatures)
{
double sum = 0.0;
double avg = 0.0;
for (int i =0; i < temperatures.length; i++)
{
if (i == -999)
{
// what technique is there to exlude and keep counting?
}
else
{
sum += i;
}
}
avg = sum / temperatures.length;
return avg;
}
Upvotes: 0
Views: 1170
Reputation: 29710
The easiest way to compute the average while filtering out any unwanted values would be:
double average = Arrays.stream(temperatures)
.filter(i -> i != -999)
.average();
Upvotes: 0
Reputation: 614
suppose you are correct with the logic but you are not getting the sum of the temperature values.
public static double averageTemperature(int[] temperatures)
{
double sum = 0.0;
double avg = 0.0;
for (int i =0; i < temperatures.length; i++)
{
if (temperatures[i] == -999)
{
continue;
}
else
{
sum += temperatures[i];
}
}
avg = sum / temperatures.length;
return avg;
}
hope this is what you are looking for.
Upvotes: 0
Reputation:
Using Java 8 you can do;
temperatures = Arrays.stream(temperatures).filter(x -> x != -999).toArray();
You can exclude any array value this way using predicate
statements.
Calculating the mean is as simple as just looping the array and dividing by the length then.
float mean;
for (int i = 0; i < temperatures.length; ++i) {
mean += (float) temperatures[i];
}
mean /= (float) temperatures.length;
Note to use a float
for the mean and cast your integer array values to float
also to avoid integer division, as well as the length
of the array.
Upvotes: 2
Reputation: 5250
This should be pretty straightforward - just use a variable as counter for the "valid" entries. You also need to access the values in the array properly. Here's a proposal (untested), which assumes "valid" entries are those not equal t0 -999 (modify the condition as you like):
public static double averageTemperature(int[] temperatures)
{
double sum = 0.0;
double avg = 0.0;
int validEntries = 0;
for (int i =0; i < temperatures.length; i++)
{
// process only "valid" entries
if (temperatures[i] != -999)
{
sum += temperatures[i];
++validEntries;
}
}
avg = sum / validEntries;
return avg;
}
Upvotes: 3