Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy a 1*9 array into a 3*3 array – Java

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(); 
      }
   }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading