Why am I getting an ArrayIndexOutOfBounds exception?
private void equal_AxB() {
int x = matrix_A.length;
int y = matrix_B[0].length;
matrix_C = new double[x][y];
for(int i = 0; i < x; i++) {
for(int j = 0; j < y; j++) {
for(int k = 0; k < y; k++){
matrix_C[i][j] += matrix_A[i][k]*matrix_B[k][j];
}
开发者_StackOverflow社区 }
}
return;
}
matrix_A:
2 3
2 3
2 3
matrix_B:
2 3 4
2 4 3
Two problems I could see:
- You need to ensure that number of
columns of
A
is equal to number of rows ofB
. If this does not hold you cannot multiply the matrices. - Your
k
loop should vary from0
toN
whereN
is number of columns of matrixA
, currently you are varying it till number of columns of matrixB
.
You have extracted the first index bound from matrix_A, and the second from matrix_B[0]; you have no guarantee that the remaining bounds relate in any way to those, so the statement:
matrix_C[i][j] += matrix_A[i][k]*matrix_B[k][j];
which accesses all dimensions of A and B may access out of bounds on any of either array's dimensions except A[i], and B[0][j].
you have written
int y = matrix_B[0].length;
as you are trying to retrieve the length of sub array of matrix_b
this will return 3 as length, so x and y now have both 3 as value but your matrix_a is 2X3 matrix, which will fails, when you try to find matrix_A at index 2.
try with int y = matrix_B.length;
this will work properly.
精彩评论