Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN JAVA! DOWNLOAD THE CODE BELOW AND FIX THE PROBLEM: THE COPY IS WRONG. public

ID: 3753247 • Letter: I

Question

 IN JAVA! DOWNLOAD THE CODE BELOW AND FIX THE PROBLEM: THE COPY IS WRONG.  public class PointerCopyProblem {      public static void main (String[] argv)     {         // Make a 3 x 2 array.         int[][] A = {             {1, 2},             {3, 4},             {5, 6}         };                  // To B, we assign space for 3 pointers:         int[][] B = new int [3][];          // Now do a pointer copy.         for (int i=0; i<A.length; i++) {             B[i] = A[i];         }          print (A, B);                  // Make a change in B.         B[0][0] = 9;                  print (A, B);     }      static void print (int[][] A, int[][] B)     {         System.out.println (" Array A: ");         for (int i=0; i<A.length; i++) {             for (int j=0; j<A[i].length; j++) {                 System.out.print (" " + A[i][j]);             }             System.out.println ();         }                  System.out.println ("Array B: ");         for (int i=0; i<B.length; i++) {             for (int j=0; j<B[i].length; j++) {                 System.out.print (" " + B[i][j]);             }             System.out.println ();         }     }      }

Explanation / Answer

Hi

I have made smal changes to copy the contents of one array to another array. Highlighted the code changes below. We can not copy array instance to another, if we do so then changes in forst array will effect to the recond array.

PointerCopyProblem.java

public class PointerCopyProblem {

public static void main (String[] argv)

{

// Make a 3 x 2 array.

int[][] A = {

{1, 2},

{3, 4},

{5, 6}

};

  

// To B, we assign space for 3 pointers:

int[][] B = new int [3][];

// Now do a pointer copy.

for (int i=0; i<A.length; i++) {

B[i] = new int[A[i].length];

for(int j=0;j<A[i].length;j++){

B[i][j] = A[i][j];

}

}

print (A, B);

  

// Make a change in B.

B[0][0] = 9;

  

print (A, B);

}

static void print (int[][] A, int[][] B)

{

System.out.println (" Array A: ");

for (int i=0; i<A.length; i++) {

for (int j=0; j<A[i].length; j++) {

System.out.print (" " + A[i][j]);

}

System.out.println ();

}

  

System.out.println ("Array B: ");

for (int i=0; i<B.length; i++) {

for (int j=0; j<B[i].length; j++) {

System.out.print (" " + B[i][j]);

}

System.out.println ();

}

}

  

}

Output:


Array A:
1 2
3 4
5 6
Array B:
1 2
3 4
5 6

Array A:
1 2
3 4
5 6
Array B:
9 2
3 4
5 6