Reputation: 25
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
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
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