Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 347
Buki Avatar asked Feb 17 '12 07:02

Buki


People also ask

How do you assign a 1D array to a 2D array in Java?

Create a 2d array of appropriate size. Use a for loop to loop over your 1d array. Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.

How do you declare and initialize 1D 2D array with an example?

Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row.

Can we use multi dimensional arrays in Java?

Java also supports arrays with more than one dimension and these are called Multidimensional arrays. => Check ALL Java Tutorials Here. The Java multidimensional arrays are arranged as an array of arrays i.e. each element of a multi-dimensional array is another array.


1 Answers

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();
}
like image 161
Juvanis Avatar answered Oct 27 '22 00:10

Juvanis