Error in code - Arrayindexoutofboundsexception

Asked

Viewed 315 times

-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 mistake is this :

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

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

BUILD FAILED (total time: 0 seconds)

The line 132 is B[i][j] = A[j][i];

  • Our official language is Português. Translate your question.

  • The index A[j][i] of array, there is no.

  • I’m transposing A into B

  • Do you know how to do a table test? https://answall.com/q/220474/5878. If the error is in row 132, while the example has not 20 lines, the error does not occur in this code. You probably tried to create a [mcve], which is good practice when asking, but the example does not reproduce the error.

  • In the code that gave the error, the matrix is not square, correct?

2 answers

1

The vector B is a matrix 2x1 and the vector To is a matrix 2x2

In that 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’re trying to manipulate a vector 2x1 as if he were a vector 2x2, then give index overflow, which is the mistake you are having.

In that part of the code

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

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

1

The problem is how you are initiating the matrix B. Try to replace:

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

for

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.