Error in code - ArrayIndexOutOfBoundsException

-1
int[][] A = {{11, 7},{-20,-22}};
     int[][] B = {{A[0].length},{A.length}};

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

        for(int j = 0; j < A[0].length;j ++){
            System.out.print(A[i][j] + "\t");


        }
    System.out.println();
    }

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

        }
    }

The error is this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1       
at j.pkg1.J1.ex31(J1.java:132)

C:\*******************************\NetBeans\Cache.2\executor-snippets\run.xml:53: Java returned: 1

BUILD FAILED (total time: 0 seconds)

Line 132 is B[i][j] = A[j][i];

    
asked by anonymous 10.03.2018 / 15:37

2 answers

1

The problem is how you are initializing array B. Try replacing:

int[][] B = {{A[0].length},{A.length}};

by

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

    
10.03.2018 / 19:40
1
The vector B is a matrix 2x1 and the vector A is a matrix 2x2

In this part of the code:

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

    for(int j = 0; j < A[0].length;j ++){
        System.out.print(A[i][j] + "\t");
    }

System.out.println();

}

You are trying to manipulate a 2x1 vector as if it were a 2x2 vector, then give index overflow, which is the error you are having. >

In this part of the code

int[][] B = {{A[0].length},{A.length}};

You are not copying the vector size A to B , you are assigning the vector length value (which is 2) to an index of the vector that is integer.

    
11.03.2018 / 04:54