Reputation: 153
Basically I have an array which holds rain data from years 1907-2007 (for example - length 100). Each element of the array contains another array with data on the amount of rain each month in that year.
My question is, how would I go about calculating the average rainfall for a user specified year? This is what I have so far:
public double calculateAverageForYear(int year){
double sum = 0.0;
for (int i=0;i<Years.length;i++){
sum = sum += Years[i].calculateAvgRain();
}
sum = sum/12;
return sum;
}
calculateAvgRain is defined in another class and is correct as far as my testing goes. Thanks for the help
Upvotes: 0
Views: 135
Reputation: 309
I will assume that the user-defined parameter int year
is not the actual index to the years
array. If it is an actual year number, you'll have to convert it depending on which is the first year in your array. It should be as easy as int index = year - 1907
, assuming year 1907 is the element with index 0.
If the menthod you used Years[i].calculateAvgRain()
works, then you probably just need to adjust that i
(as mentioned above). You don't need a loop then.
Since you're asking a question it is probably something else that is the problem. I'll assume you have 100x12 array with years as rows and month rain data in the columns.
public double calculateAverage(int year) {
int index = year - 1907; //extract 1907 into a CONSTANT or some other variable if possible
double sum = 0.0;
for (double monthRain : years[index]) { //is `years` visible?
sum += monthRain;
}
return sum / years[index].length; //`years[index].length` should be 12, but maybe you have a blank month data?
}
Please, do correct me and clarify the problem in a bit more detail.
Upvotes: 1