I'm trying to copy a 1 by 9 array into a 3 by 3 array. I'm not sure why my output is just the number 1 moving across the array. Any help would be greatly appreciated.
public class arrayTest{
public static void main(String [] args)
{
int A [] = {1,2,3,4,5,6,7,8,9};
int B [][] = new int [3][3];
int i = 0, k, j;
for(k = 0; k < 3; k )
for(j = 0; j < 3; j ){
B[k][j] = A[i];
k ;
}
for(k = 0; k < 3; k )
{
for(j = 0; j< 3; j )
System.out.print(B[k][j] " ");
System.out.println();
}
}
}
CodePudding user response:
You need to convert the 2D coordinates from the loop counters into an index into the 1D array:
int A [] = {1,2,3,4,5,6,7,8,9};
int B [][] = new int [3][3];
for (int k=0; k < 3; k ) {
for (int j=0; j < 3; j ) {
B[k][j] = A[k*3 j];
}
}
System.out.println(Arrays.deepToString(B));
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]