2014-02-11 18 views
0

我想輸入我自己的VALUE到20的大數組並將其複製到10的2個小數字中,那麼第二個數組的值必須是outprinted。我得到錯誤ArrayIndexOutOfBoundsException我的代碼有什麼問題。 = |我想從大的ARR複製到兩個小的

Scanner in = new Scanner(System.in); 
     int[] test = new int[20]; 
     int[] testA = new int[10]; 
     int[] testB = new int[10]; 
     for (int i = 0; i < test.length; i++){ 
      test[i] = in.nextInt(); 
     } 
     for(int i = 0; i < 10; i++){ 
      testA[i]= test[i]; 
     } 
     for (int i = 10; i < test.length; i++){ 
      testB[i] = test[i]; 
      System.out.println(testB[i]); 

回答

1

在第二循環的第一步驟中,將值分配給testB[10],這會導致錯誤,因爲只testB具有10(即[0~9])的大小。

您需要更改

testB[i] = test[i]; 
System.out.println(testB[i]); 

testB[i-10] = test[i]; 
System.out.println(testB[i-10]); 

或者你可以使用:

for (int i = 0; i < 10; i++){ 
    testB[i] = test[i+10]; 
    System.out.println(testB[i]); 
} 
+0

它的工作。咦?但是他開始從10開始計數並上升到20,而當他這樣做的時候,他從另一個陣列中複製價值觀,我沒有得到,爲什麼有[i - 10]? –

+0

@Predict_it通過做'testB [i] = test [i];',你認爲'testB'和'test'的速度是一樣的,這是錯誤的。 – herohuyongtao

+0

所以它就像是從測試的價值回落,或者你切斷測試的開始位置,以 –

1

Alternativley:

System.arraycopy(test , 0, testA , 0, 10); 
System.arraycopy(test , 10, testB , 0, 10); 
相關問題