所以这个方法的目的是得到一个高于100的温度数组。这有什么问题?当我在toString中返回它时,它说blazing []不存在。
public int[] above100Degrees()
{
int[] blazing = new int[temps.length];
for( int i = 0; i < temps.length; i++ )
{
if( temps[i] > 100 )
{
blazing[i] = temps[i];
}
}
return blazing;
}
toString方法:
public String toString()
{
String returnString = "The temperature forecast of week " + WEEK + " is logged in as: ";
for( int i = 0; i < temps.length; i++ )
{
returnString += "\t" + temps[i] + "\t";
}
returnString += "\n" + "The number of temperatures below freezing is " + getUnderFreeze() + "." + "\n" +
"The largest difference this week was a net change of " + NetChange() + ".";
for( int i = 0; i < blazing.length; i++ )
{
returnString += "The temperature above 100 degrees is " + above100Degrees() + "." + "\n" + "\t" + blazing[i] + "\t";
}
return returnString;
}
输出
Forecast.java:122: error: cannot find symbol
for( int i = 0; i < blazing.length; i++ )
^
symbol: variable blazing
location: class Forecast
Forecast.java:124: error: cannot find symbol
returnString += "The temperature above 100 degrees is " + above100Degrees() + "." + "\n" + "\t" + blazing[i] + "\t";
^
symbol: variable blazing
location: class Forecast
2 errors
答案 0 :(得分:5)
数组由above100Degrees
方法返回。它不会在调用它的范围内建立变量名blazing
。实际上,您可以将返回的数组分配给名为different的变量。
尝试
int[] reallyHot = above100Degrees();
// Then check reallyHot...
for( int i = 0; i < reallyHot.length; i++ )
{
returnString += "The temperature above 100 degrees is " + reallyHot[i] + "." + "\n";
}
确保使用数组访问语法访问特定元素。
答案 1 :(得分:2)
更改:
for( int i = 0; i < blazing.length; i++ )
{
returnString += "The temperature above 100 degrees is " + above100Degrees() + "." + "\n" + "\t" + blazing[i] + "\t";
}
到:
int[] blazing = above100Degrees();
for( int i = 0; i < blazing.length; i++ )
{
returnString += "The temperature above 100 degrees is " + blazing[i] + "."; // personalise format
}
答案 2 :(得分:2)
你的above100Degrees()函数返回数组blazing,但是你没有在toString()方法中调用该函数。就toString()而言,不存在炽热。
从toString()中调用above100Degrees()并将结果数组保存到变量中。然后你就可以迭代(newVariable).length而不是blazing.length。