Reputation: 1562
Should I point out that I am a begginer at this?
double averageMonthlyTemp() {
double[] amt = new double[52];
int sum = 0;
int index = 0;
for (int i = 0; i < temp.length - 1; i = i + 7) {
//where temp is an existiing
//previously initialized array
//of 365 elements, form 0 to 364
for (int j = 0; j < 7; j++) {
sum = sum + temp[i + j];
if (j % 7 == 6) {
double average = ((double) sum) / 7;
amt[index] = average;
index++;
sum = (int) 0;
}
}
}
return amt;
}
When I try to compile, I get an "incompatible types" error, with the "amt" at return amt
marked in red. Does somebody know why?
Upvotes: 1
Views: 149
Reputation: 13
the returned value amt is double[]
. But the function returns only a double
value (not an array of double ). so try to rename the function as
double [] averagemonthlytemp()
{
}
Upvotes: 1
Reputation: 2369
Your method averageMonthlyTemp
is specified to return some value of type double
, but your amt
variable is actually a double[]
. Either make averageMonthlyTmp
return an array of double
s, or do something like this:
double averageMonthlyTmp(int month) {
...
return tmp[month]; // could be made more efficient by only calculating the temperature for one month
}
A couple of additional notes about the code:
j
goes from 0 to 6 inclusive, the if (j % 7 == 6)
can be replaced with if (j == 6)
. Also, it looks like that code (computing the average) can go directly after the second for
loop.i = i + 7
with i += 7
, which will also increase i
by 7 each time.(int)
before the 0 in the line sum = (int) 0;
, because Java knows that when you just write 0
, you mean an int
.Upvotes: 4
Reputation: 629
your method definition for averageMonthlyTemp
says that it is supposed to return a double
, that is a single value of datatype double
but you are returning amt
which is a double array, that is why the compiler complains. So you can either change the method definition to return an array or return a single value.
Upvotes: 1