運行這段代碼給了我一個數組越界異常在該行:問題與ArrayIndexOutOfBoundsException異常
int sum = array[k]+array[l]; //sum of l and k
...應該是一個簡單的修復,但我想不出什麼可以導致它,因爲我使用array.length來綁定循環。誰能幫忙?
P.S.對於記錄來說,這段代碼應該搜索一個int數組,以獲得等於目標int的整數或單個整數。它僅使用println的工作,但我試圖將加入目標的數字放入向量中。
public Vector<Vector<Integer>> subsetSum(int[] array, int target) {
//creates vectors, adds inner vector to another vector
outer = new Vector<Vector<Integer>>();
inner = new Vector<Integer>();
outer.add(inner);
for (int k = 0; k <= array.length; k++) {
for (int l = 0; l <= array.length; l++) {
int sum = array[k]+array[l]; //sum of l and k
int i = 0;
if (sum == target) {
inner.add(i, array[l]);
inner.add(i, array[k]);
i++;
//prints combination
System.out.println(array[l]+"+"+array[k]+"="+target);
}
if (k == target) {
inner.add(i, array[k]);
i++;
//prints if int equals target
System.out.println(k+"="+target);
}
if (l == target) {
inner.add(i, array[l]);
i++;
//prints if int equals target
System.out.println(l+"="+target);
}
}
}
//return combinations that add up to target in vector form
System.out.println(outer);
return outer;
}
這確實修復了錯誤......謝謝! –