Array problem for matrix multiplication program
843785Oct 12 2008 — edited Oct 12 2008Hey, I've written this program using arrays for matrix multiplication. It compiles but when I try to run it is says the following error message:
"Matrix 1:
1 0 1Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MatrixMultiply.main(MatrixMultiply.java:20)
What does this mean and how do I fix it! The following is my code:
{code}public class MatrixMultiply{
public static void main(String[] args)
{
int[][]matrixA = {{1, 0, 1},
{1, 2, 3},
{1, 4, 5}};
int[][]matrixB = {{5, 4, 0},
{4, 8, 1},
{1, 1, 0}};
int matrixC[][] = new int[3][3];
int x= matrixA.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j <= x; j++) {
System.out.print(" "+ matrixA[i][j]);
}
System.out.println();
}
int y= matrixB.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < y; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+matrixB[i][j]);
}
System.out.println();
}
for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
for(int k = 0; k < y; k++){
matrixC[i][j] += matrixA[i][k]*matrixB[k][j];
}
}
}
System.out.println("Multiply of both matrix : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+matrixC[i][j]);
}
System.out.println();
}
}
}
{code}