Buki Buki - 25 days ago 8
Java Question

populating 2d array with two 1d arrays in java

I have 2 1d arrays and im trying to populate them into a single 2d array in JAVA.

For instance:

x[] = {2,5,7,9}
y[] = {11,22,33,44}


The results should then be:

result[][] = {{2,5,7,9}, {11,22,33,44}}


How do I go about this? I currently have something like this:

for(int row = 0; row < 2; row++) {
for(int col = 0; col == y.length; col++) {
???
}
}


Im sort of stuck from there...

Answer

2D array is an array of arrays. So why don't you try this?

int result[][] = {x,y};

And to make sure that it is so simple and works, test this:

for(int i=0; i<result.length; i++)
{
    for(int j=0; j<result[0].length; j++)
        System.out.print(result[i][j]+ " ");
    System.out.println();
}