[英]incompatible types in java
Should I point out that I am a begginer at this? 我应该指出我对此是一个乞gg吗?
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. 尝试编译时,出现“不兼容类型”错误, return amt
处的“ amt”标记为红色。 Does somebody know why? 有人知道为什么吗?
Your method averageMonthlyTemp
is specified to return some value of type double
, but your amt
variable is actually a double[]
. 指定您的方法averageMonthlyTemp
以返回一些double
类型的值,但是您的amt
变量实际上是double[]
。 Either make averageMonthlyTmp
return an array of double
s, or do something like this: 使averageMonthlyTmp
返回一个double
数组,或者执行以下操作:
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)
. 因为j
从0到6(含0),所以if (j % 7 == 6)
可以替换为if (j == 6)
。 Also, it looks like that code (computing the average) can go directly after the second for
loop. 同样,看起来代码(计算平均值)可以在第二个for
循环之后直接执行。 i = i + 7
with i += 7
, which will also increase i
by 7 each time. 在您的第一个for循环中,如果将i = i + 7
替换为i += 7
,则代码会更整洁,这也会使i
每次增加7。 (int)
before the 0 in the line sum = (int) 0;
您无需在sum = (int) 0;
行中将(int)
放在0之前sum = (int) 0;
, because Java knows that when you just write 0
, you mean an int
. ,因为Java知道当您只写0
,就意味着一个int
。 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. 您对averageMonthlyTemp
的方法定义说应该返回double
,即数据类型double
的单个值,但是您返回的amt
则是一个double数组,这就是编译器抱怨的原因。 So you can either change the method definition to return an array or return a single value. 因此,您可以更改方法定义以返回数组或返回单个值。
the returned value amt is double[]
. 返回的值amt是double[]
。 But the function returns only a double
value (not an array of double ). 但是该函数仅返回一个double
值(而不是double的数组)。 so try to rename the function as 所以尝试将函数重命名为
double [] averagemonthlytemp()
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.