我想實現一個簡單的函數,它將數字添加到現有的數組,但我在下面的代碼中得到一個錯誤,一個異常正好在函數addArrayToNumber行:「數字+ = NUMBERS_ARRAY [i]「。我不想趕上例外,只是修復代碼。異常在線程,函數添加數組到數組
public class Main {
private static final int[] NUMBERS_ARRAY = {1, 2, 3, 4, 5};
public static final void main(String[] args) {
int x = addArrayToNumber(1);
System.out.println("X = " + x);
int y = addArrayToNumber(10);
System.out.println("Y = " + y);
}
private static int addArrayToNumber(int number) {
for (int i = 0; i <= NUMBERS_ARRAY.length; i++) {
number += NUMBERS_ARRAY[i]; /** here it is */
}
return number;
}
'對(INT I = 0;我
這麼簡單的錯誤,謝謝。 – Soothsayer92
讓我由12s。是的,最常見的錯誤是簡單的錯誤。注意堆棧跟蹤,我敢打賭它說ArrayIndexOutOfBoundsException,所以自然你應該先檢查邊界。 – Luke