2012-12-02 72 views
-1

我試圖拆分一個數組,將一部分存儲在一個數組中,另一部分存儲在另一個數組中。然後即時嘗試翻轉2並將它們存儲在一個新的數組中。這裏是我有java.lang.ArrayIndexOutOfBoundsException錯誤?

public int[] flipArray(){ 
     int value = 3; 
     int[] temp1 = new int[value]; 
     int[] temp2 = new int[(a1.length-1) - (value+1)]; 
     int[] flipped = new int[temp1.length+temp2.length]; 

    System.arraycopy(a1, 0, temp1, 0, value); 
    System.arraycopy(a1, value+1, temp2, 0, a1.length-1); 
    System.arraycopy(temp2, 0, flipped, 0, temp2.length); 
    System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
      return flipped; 
    } 
    private int[]a1={1,2,3,4,5,6,7,8,9,10}; 
+2

嗨,請你可以發佈異常消息,因爲它會告訴我們哪一行代碼給出的數組索引超出了界限錯誤。 – ThePerson

+0

可能的重複[什麼導致java.lang.ArrayIndexOutOfBoundsException,我該如何防止它?](http://stackoverflow.com/questions/5554734/what-c​​auses-a-java-lang-arrayindexoutofboundsexception-and-how- DO-I-防止-IT) – Raedwald

回答

0

你的索引和數組長度關閉:

public int[] flipArray(){ 
    int value = 3; 
    int[] temp1 = new int[value]; 
    int[] temp2 = new int[a1.length - value]; 
    int[] flipped = new int[a1.length]; 

    System.arraycopy(a1, 0, temp1, 0, value); 
    System.arraycopy(a1, value, temp2, 0, temp2.length); 
    System.arraycopy(temp2, 0, flipped, 0, temp2.length); 
    System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
    return flipped; 
} 
private int[]a1={1,2,3,4,5,6,7,8,9,10}; 

的關鍵是要明白,System.arraycopy沒有最後索引處的元素複製。

0

除掉不必要操縱帶有索引:

public int[] flipArray(){ 
int value = 3; 
int[] temp1 = new int[value]; 
int[] temp2 = new int[a1.length - value]; 
int[] flipped = new int[temp1.length+temp2.length]; 

System.arraycopy(a1, 0, temp1, 0, value); 
System.arraycopy(a1, value, temp2, 0, temp2.length); 
System.arraycopy(temp2, 0, flipped, 0, temp2.length); 
System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
} 
1

當你想的範圍外訪問數組元素你獲得的ArrayIndexOutOfBoundsException異常[0,長度 - 1];

如果您使用調試器,或者在每次調用System.arraycopy之前放置一個System.out.println(text),您可以自己找到probelm,您可以在其中輸出源和目標數組的長度以及元素的數量複製

0

此行是錯誤的:

System.arraycopy(a1, value+1, temp2, 0, a1.length-1); 

您從位置4開始,想複製9個元素。這意味着它會嘗試從數組中的索引4到12複製元素。

相關問題