Member Avatar for mjv89

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();

        }
    }
}

Recommended Answers

All 2 Replies

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.

Member Avatar for mjv89

It works!

Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.