Java 如何使数组的大小成为for循环返回的结果?

Java 如何使数组的大小成为for循环返回的结果?,java,arrays,for-loop,Java,Arrays,For Loop,我需要数组的大小为我在for循环中迭代过的大小。现在它说我的返回“数组”没有找到 public int[] method(int[] a, int red, int yellow) { for (int i = 0; i < length; i++) { int[] array = new int[i]; array[i] = a[i]; } public int[]方法(int[]a,int红色,int黄色){ 对于(int i=0;i

我需要数组的大小为我在for循环中迭代过的大小。现在它说我的返回“数组”没有找到

public int[] method(int[] a, int red, int yellow) {

for (int i = 0; i < length; i++) { 
     int[] array = new int[i];

        array[i] = a[i]; 


}
public int[]方法(int[]a,int红色,int黄色){
对于(int i=0;i
正如您在for循环内部定义了
数组一样,变量数组的作用域在for循环结束时结束。这就是为什么编译器在返回时找不到
数组
变量的原因。尝试在for循环之前移动
数组
变量。

您应该在循环外部定义数组。一旦在循环内声明,其作用域将限于循环

如果您认为根据您的逻辑这是有意义的,您可以尝试下面的代码。但是,您将面临另一个问题,即此
IndexOutOfBoundException
。我建议调试并在您的逻辑上做更多工作

    int[] array = null;
    for (int i = 0; i < a.length; i++) {
        array = new int[i];
        if (a[i] >= red && a[i] <= yellow) {
            array[i] = a[i];

        }

    }
    return array;
int[]数组=null;
for(int i=0;i=red&&a[i]
试试这个。你也不能在for循环中返回数组

公共静态void main(字符串arg[]){

int[]a={1,2,3,4,5,6};
方法(a,1,4);
}
公共静态无效方法(int[]a,int x,int y){
int[]数组=新的int[a.length];
对于(inti=0;i如果(a[i]>=x&&a[i]
array
需要在
for
循环的
范围之外定义,并使用
a.length
的大小初始化,而不是
i
我尝试过这样做,但似乎没有相应地调整长度。
    int[] a={1,2,3,4,5,6};
    method(a,1,4);
}
public static void method(int[] a, int x, int y) {
    int[] array = new int[a.length];
    for (int i = 0; i < a.length; i++) { 

         if (a[i] >= x && a[i] <= y) { 
            array[i] = a[i]; 

         }

      }
    System.out.println(Arrays.toString(array)); 
}