Cosmik11
Cosmik11

Reputation: 25

1D array to 2D array in java

im trying to convert this 1D array to a 2D array but I cant get it to work.

 public static void main ( String args []  ){
int [] scanned={1,2,3,4,5,6,7,8,9,10,11,12};

int row=4;
int col=3;

int[][] skydata=new int[row][col];

   for(int r=0; r<row; r++){

    for( int c=0; c<col; c++){

        for(int i=0; i<row*col; i++){
            skydata[r][c]=scanned[i];
        }
    }

}


System.out.print(Arrays.deepToString(skydata));

this gives an output of the last element [[12,12,12] [12,12,12] etc.

my goal is to copy it so that the 2d array outputs as follows [[1,2,3],[6,5,4][7,8,9],[12,11,10]

so what Am i doing wrong?

Upvotes: 0

Views: 6664

Answers (2)

Cosmik11
Cosmik11

Reputation: 25

    int k = 0;

    for(int r = 0; r<row; r++)
    { 
       if(r % 2 == 0){

        for(int c = 0;  c< col; c++)
        {
           skydata=[r][c]=scanned[k];
           k++;
       }
    }

         else {

                 for (int c=col-1; c>=0 c--)
            {
               skydata[r][c]=scanned[k];
            k++;
        }
    }
}

Nevermind I tried this and it ended up working for me

Upvotes: -1

i_rezic
i_rezic

Reputation: 372

public static void main ( String args []  ){
int [] scanned={1,2,3,4,5,6,7,8,9,10,11,12};

int row=4;
int col=3;

int[][] skydata=new int[row][col];
int i = 0;
   for(int r=0; r<row; r++){

    for( int c=0; c<col; c++){
            skydata[r][c]=scanned[i++];
    }

}


System.out.print(Arrays.deepToString(skydata));

Try this. Problem was with this for loop:

for( int c=0; c<col; c++){
            skydata[r][c]=scanned[i++];
    }

as i variable would each time start from all over again. You can try to write variables on paper and see that i doesn't go larger that 1, because you initialize it withe every new iteration in second for loop.

Upvotes: 3

Related Questions