How can I copy a 2d array to a new and bigger one with eye for adding more items in the new one while still having the original data? My code makes out of bounds failure - what is my mistake? I try to say that the copy array should be original array.length x - but doesn't work.
import java.util.Scanner; // import scanner to the program
public class TestTest {
// Declaring Scanner object.
public static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// Variables
int number = 1;
// Declaring 2d Array
int[][] myArray = new int [3][3];
// Loop values into the array
for(int i =0; i<myArray.length; i )
{
myArray[i][0]= number;
number ;
myArray[i][1]= (int) (Math.random () * 10) 1;
myArray[i][2]= (int)(Math.random() * ((1000 - 100) 1)) 100;
}
// Print the original array
System.out.println("This is original array:");
for(int i =0; i<myArray.length; i )
{
System.out.println(myArray[i][0] " " myArray[i][1] " " myArray[i][2]);
}
// Make a copy of the original array and expand the length with 3.
int[][] copyArray =new int[myArray.length 3][3];
for (int i = 0; i < copyArray.length; i)
{
copyArray[i] = new int[myArray[i].length];
for (int j = 0; j < copyArray[i].length; j)
{
copyArray[i][j] = myArray[i][j];
}
}
// Print the copy
System.out.println("This is the copy:");
for (int i = 0; i < copyArray.length 3; i)
{
System.out.println(copyArray[i][0] " " copyArray[i][1] " " copyArray[i][2] );
}
}
}
CodePudding user response:
You're getting ArrayIndexOutOfBounds
because array copyArray
has greater length than your source array myArray
.
Therefore, when index i
exceeded the length of the source array, this line would cause an exception:
copyArray[i] = new int[myArray[i].length];
Because there would be no nested array referred by myArray[i]
.
CodePudding user response:
Try it like this
int[][] copyArray =new int[myArray.length 3][3];
for (int i = 0; i < myArray.length; i) { // length of myArray
copyArray[i] = new int[myArray[0].length]; // 0 instead of i
for (int j = 0; j < myArray[i].length; j) { // length of myArray
copyArray[i][j] = myArray[i][j];
}
}
Also since copyArray has already increased size you don't need the 3 in the last for loop. Hope I helped, good luck