0

Hi,

I'm trying to learn more about matrices in Java.

I am trying to read in two integer matrices A and B, then print
out the calculation for A + B, but I am getting an ArrayIndexOutOfBoundsException on line 21.

Any help would be greatly appreciated.

class MatrixAdd {

public static void main(String[] args)  {
    
int array[][]= {{0,1},{3,4}};

int array1[][]= {{5,4},{2,1}};

System.out.println("Number of Rows= " + array.length);

System.out.println("Number of Columns= " + array[1].length);

int l= array.length;

System.out.println("Matrix 1 : ");

for(int i = 0; i < l; i++) {

for(int j = 0; j <= l; j++) {
    
System.out.print(" "+ array[i][j]);

}

System.out.println();
}

int m= array1.length;

System.out.println("Matrix 2 : ");

for(int i = 0; i < m; i++) {

for(int j = 0; j <= m; j++) {

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

}  
System.out.println();

}

System.out.println("Addition of both matrix : ");

for(int i = 0; i < m; i++) {
    
for(int j = 0; j <= m; j++) {

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

}

System.out.println();

        }
    }
}
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by mjv89
0

Your second loop is going to j<=l - since l is array.length, this takes you over the edge - you're trying to access array[0][2]

Change the <= to < and you should be okay.

0

It works!

Thank you very much.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.