Can anyone help with a homework problem I am doing? Basically the program I am trying to create asks the user for an integer N and then for two separate sets of N integers, these sets are stored in two separate arrays (x and y), and then a function mixReverse(a, b) is called with x and y as the parameters. The mixReverse(x,y) function reverses the order of the elements in the y array, and then interleaves the elements of each array into one final array so that the finalArray consists of arr1[0], arr2[arr2.length-1], arr1[1], arr2[arr2.length-2], ... arr1[arr1.length-1], arr2[0].
I am have tried this code, but it's problematic:
finalArray[0] = arr1[0];
finalArray[1] = arr1[0];
for (int j=2; j<(2*arr1.length); j++) {
if (j%2==0) {
finalArray[j] = arr1[j/2];
}
else {
finalArray[j] = arr2[(((j+1)*(2))-1)];
}
}
Specifically this line: finalArray[j] = arr1[j/2];
is throwing the error:
java.lang.ArrayIndexOutOfBoundsException: 7
at lab2part1.mixReverse(lab2part1.java:33)
at lab2part1.main(lab2part1.java:15)
I know that the error is "Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array." but I cant figure out why the index is illegal. Then length of the array is 2*(arr1.length), so this for loop should work properly. J is never negative and never equal to anything more than arr1.length -1 (which is equal to the final index of finalArray). Can anyone assist me in finding a solution?
finalArrayinitialized?System.out.printlnor similar) to verify that things are as you think they are at various points in the execution? Have you tried anything at all?finalArray? Maybe you're accidentially creating it too small.