Would appreciate your help with 2d Array..

• 02-11-2008, 06:17 AM
cloudkicker
Would appreciate your help with 2d Array..
Hello Everyone,

I am new to Java and new to Java Forums. I would really appreciate it if someone can help me understand how I can do this task. I am learning java via online tutorials and couple of books. What I want to do is to populate a multidimensional array's elements with another arrays elements such as:

I declare two arrays:

1. moon[][] is multidimensional array
2. m in a array with assigned elements

I would like to take elements of Array m and assign them to the rows of the moon and then take the Array m elements again and multiply them by 3 and then assign them to the columns of Array moon. Any help would highly be appreciated .

Thank you.

Code:

``` public class 2dArray {           public static void main( String args[] )     {       int[][] moon = new int [10][4];       int[] m = {1, 2, 3, 4, 5, 6};       for (int j=0; j < m.length; j++)         {             moon[j][j*3] = m[j];  //  THIS IS WHERE I AM HAVING AN ISSUE                         System.out.println(moon[j][j] + " " );           }                         System.out.println();                         // print array in rectangular form                         for (int r=0; r < moon.length; r++)                         {                             for (int c=0; c < moon[r].length; c++)                             {                                 System.out.print(" " + moon[r][c]);                             }                             System.out.println(" ");                         }           } }```
• 02-11-2008, 03:34 PM
hey
Hi,

fisrst, how do you like to assign 6 numbers to your moon arrray ?
moon looks like this

? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ?

you have just 6 numbers, so you can do

1 2 3 4 5 6 ? ? ? ?
? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ?
Is it what you want?

next,
to get an element from 2d array, you need to indicate both dimensions: moon[?][?], for instance you need to do moon[0][1]to get an element from the last array
Therefore, you need to use two loops to get each element in the 2d array (unless you wanna do it as in the previous array, if you do, you need to indicate, for example, first dimension as 0)

next, you write:
moon[j][j*3] = m[j];
when you do it that way, you get element, which is located on the crossing of the j raw and j*3 column, this is obviously not what you want to do,
again,you need to use two loops and two variables (i,j) to track all the elements, second to multiply element, you will need to do this
moon[i][j]=m[i]*3;

I am not sure if I understood your idea, but these are some comments