如何使用其他方法中的变量?(找不到符号-变量evenNum)



我正在编写一个只打印数组偶数的代码。但是我在将evenNum变量从countEm发送到getAllEvens时遇到问题。

private static int countEm(int[] array)
{
int evenNum = 0;
for (int i = 0; i <array.length; i++)
{
if (i%2 == 0)
{
evenNum++;
}
}
return evenNum;
}
public static int[] getAllEvens(int[] array)
{      
int[] evens = new int [evenNum];
int c = 0;
for(int i = 0; i < array.length; i++)
{
if(array[i]%2==0)
{
evens[c] = array[i];
c++;
}
}
return evens;   
}

如何使用其他方法中的变量?

这样,gettAllEvents将永远无法访问evenNum。

您应该在函数countEm之外声明它

最新更新