2010-12-14 58 views
0

我有一個異常問題「java.lang.ArrayIndexOutOfBoundsException」 我寫了一個程序,它具有48長度的src數組然後處理它以每6個索引另一個數組使用方法arrayCopy並打印每個dst數組對我來說,它工作正常,它打印從初始數組中的每個6個索引,但最終我得到一個異常幫助。該算法只是一個測試,因爲我想在另一個算法中使用arrayCopy,所以我不需要建議來改變算法。我希望這是明確的足夠公平我有一個異常問題「java.lang.ArrayIndexOutOfBoundsException」

public static void main(String [] arg) 
     { 
      int[] src = new int[48]; 
      for(int j=0;j<src.length;j++) 
      { 
       src[j]=j+1; 
       System.out.print(src[j]+" "); 
      } 
      System.out.println(); 
      int[] dst = new int[6]; 
      int from=0; 
      for(int i=0;i<src.length;i++) 
      { 
       System.arraycopy(src, from, dst, 0, 6); // Copies 6 indexes from src starting at from into dst 
       from=from+6; 
       print(dst); 
       System.out.println(); 
      } 



      } 

     public static void print(int [] dst) 
     { 
      for(int i=0;i<dst.length;i++) 
       System.out.print(dst[i]+" "); 
     } 
+0

你能指出拋出異常的確切位置嗎? – jjnguy 2010-12-14 15:21:08

回答

3

試試這個:

for(int i=0;i<src.length;i+=6) // increment i by value 6 

或者在使用from表達:

for(int from=0; from<src.length; from+=6) { 
    System.arraycopy(src, from, dst, 0, 6); 
    print(dst); 
    System.out.println(); 
} 
+0

是的,我認爲這看起來像解決方案。 – jjnguy 2010-12-14 15:22:56

+0

謝謝你的工作,喜歡你的答案和(星* Infinity) – Gain 2010-12-14 15:29:18

0

你寫它,就上了路從大於47的+ 5 = 53迭代你的循環(因此超出源的範圍)。

相關問題