Reputation: 57
So I'm having some trouble with this in java. This method is supposed to take in two String arrays which are multidimensional. This method is supposed to return a a copy String array. Now these two arrays that are being sent to the copy method are going to have randomly generated lengths within the arrays. I am trying to see if array2 is smaller than array and if it is then array will be assigned the length of array2 and I want to copy elements from array into array2. If it is the opposite with array2 being bigger than array then I would like to copy the elements from array into array2 and then the REMAINING spots in array2 will get filled with an *. Now the issue is I keep getting runtime errors with out of bounds for the index. It is specifically the lines that I have indicated with double asterisks below(within for loops) that are giving me issues. What could I do to solve the issue.
public static String[][][] copy(String[][][] array, String[][][] array2){
if(array2.length < array.length){
array = new String[array2.length][array2.length][array2.length];
for(int i = 0; i < array2.length; i++){
for(int j = 0; j < array2[i].length; j++){
for(int k = 0; k < array2[i][j].length; k++){
**array2[i][j][k] = array[i][j][k];**
}
}
}
return array2;
}
if(array2.length > array.length){
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
for(int k = 0; k < array[i][j].length; k++){
**array2[i][j][k] = array[i][j][k];**
}
}
}
for(int i = array.length - 1; i < array2.length; i++){
for(int j = array[i].length - 1; j < array2.length; j++){
for(int k = array[i][j].length - 1; k < array2.length; k++){
array2[i][j][k] = "*";
}
}
}
return array2;
}
return array;
}
Upvotes: 0
Views: 48
Reputation: 38639
You assume that each dimension of the array is of equal size.
But you cannot even assume that two sibling arrays are of equal size.
What I mean is, that array = new String[array2.length][array2.length][array2.length];
is nonsense and at least in two ways.
You probably want to have array2 = new String[array.length][][]
, because if you reassign array
you will just copy null
s around. And for the lengths of the other dimensions you have to do the same comparisons and resizings, especially if you did not reassign the array2
. If you did, then you have to create the sub-level arrays afresh anyway.
Upvotes: 1