0

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?

Cosmik11
  • 25
  • 1
  • 7

2 Answers2

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

i_rezic
  • 372
  • 1
  • 15
  • Welcome to Stack Overflow! While you may have solved this user's problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem. – Joe C Apr 09 '17 at 20:38
  • it worked what was my code doing wrong would care to explain the logic? – Cosmik11 Apr 09 '17 at 20:40
  • by saying i++ inside scanned wouldnt that make you skip the first element of the 1D array – Cosmik11 Apr 09 '17 at 20:43
  • I have added explanation to my answer, feel free to mark it as solution if you find it so :) – i_rezic Apr 09 '17 at 20:44
  • @Cosmik11: row * col = 12. It puts 12 in every part of the array, because the last loop is designed to do this. It will put all your values into every part of the 2D array, stopping at 12, which is why you only see 12 everywhere. But apart from that: You seem to misunderstand 2D arrays. The last loop doesn't make sense at all and it is hard to explain the logic why it doesn't because it's so far away from anything logical. I cannot follow ur thoughts on that. – codepleb Apr 09 '17 at 20:44
-1
    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

Cosmik11
  • 25
  • 1
  • 7