這裏是你的代碼作爲SSCCE,與另外一個有用的調試語句。
import java.util.Arrays;
public class MoreArrayProblems
{
public static final void main(String[] ignored) {
System.out.println(Arrays.toString(
(new MoreArrayProblems()).everyOther(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})));
}
public int[] everyOther (int [] a){
if (a.length < 2){
return a;
}
int []l = new int[a.length/2];
//if (a.length%2==0) {int l[]= new int [a.length/2];}
//else {l[] = int [a.length + 1/2];}
int loc= 0, i = 1;
while (i<a.length){
System.out.println("l.length=" + l.length + ", a.length=" + a.length + ", i=" + i + ", [i - 1]=" + (i - 1) + "");
l[i] = a[i-1]; //for some reason this doesn't work
i += 2;
}
return l;
}
}
輸出:
[C:\java_code\]java MoreArrayProblems
l.length=5, a.length=10, i=1, [i - 1]=0
l.length=5, a.length=10, i=3, [i - 1]=2
l.length=5, a.length=10, i=5, [i - 1]=4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at MoreArrayProblems.everyOther(MoreArrayProblems.java:21)
at MoreArrayProblems.main(MoreArrayProblems.java:5)
的第一元件在陣列中具有索引的0
,不1
。這個事實以及上面的調試結果揭示了一些相當大的問題。
請描述該錯誤。它說什麼? –
java.lang.ArrayIndexOutOfBoundsException:3 \t在MoreArrayProblems.everyOther(MoreArrayProblems.java:22) – tim
這是一個運行時間錯誤 – tim