[英]How can I make the size of my array the result of what my for loop returns?
我需要我的數組是我曾經迭代過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];
}
正如您在for循環中定義了array
一樣,變量數組的范圍在for循環結束時結束。 這就是編譯器在返回時無法找到array
變量的原因。 嘗試在for循環之前移動array
變量。
您應該在循環外定義數組。 一旦在循環內聲明了變量,它的作用域將限制在循環中。
如果你認為這根據你的邏輯是有意義的,你可以嘗試下面的代碼。 但是,您將面臨此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;
試試這個。你也不能在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));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.