Pat*_*ens 0 java arrays logic return
所以这个方法的要点是得到一个高于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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
产量
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
Run Code Online (Sandbox Code Playgroud)
该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";
}
Run Code Online (Sandbox Code Playgroud)
确保使用数组访问语法访问特定元素.