Reputation: 233
I want to input my own vallues to big array of 20 and copy that to 2 small ones of 10, then value of second array must be outprinted. Im getting error ArrayIndexOutOfBoundsException what is wrong with my code. =|
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]);
Upvotes: 0
Views: 53
Reputation: 50667
In the first step of the second loop, you will assign value to testB[10]
, which causes the error because testB
only have size of 10
(i.e. [0~9]
).
You need to change
testB[i] = test[i];
System.out.println(testB[i]);
to
testB[i-10] = test[i];
System.out.println(testB[i-10]);
Or you can use:
for (int i = 0; i < 10; i++ ){
testB[i] = test[i+10];
System.out.println(testB[i]);
}
Upvotes: 1
Reputation: 654
Alternativley:
System.arraycopy( test , 0, testA , 0, 10 );
System.arraycopy( test , 10, testB , 0, 10 );
Upvotes: 1