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

时间:2018-05-24 04:40:49

标签: 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]; 


}

3 个答案:

答案 0 :(得分:1)

正如您在for循环中定义了<?PHP $REFERRER = $_SERVER['HTTP_REFERER']; // Or other method to get a URL for decomposition $domain = substr($REFERRER, strpos($REFERRER, '://')+3); $domain = substr($domain, 0, strpos($domain, '/')); // This line will return 'en' of 'en.example.com' $subdomain = substr($domain, 0, strpos($domain, '.')); //Echo $subdomain; header("Location: https://example2.com/'$subdomain"); ?> 一样,当for循环结束时,变量数组的范围结束。这就是编译器在返回时无法找到array变量的原因。尝试在for循环之前转换array变量。

答案 1 :(得分:1)

您应该在循环外定义数组。一旦在循环内声明了变量,它的作用域将限制在循环中。

如果你认为根据你的逻辑这是有意义的,你可以尝试下面的代码。但是,您将面临此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;

答案 2 :(得分:1)

  

试试这个。你也不能在for循环中返回数组

public static void main(String arg []){

    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)); 
}

}