-4

I am learning Java for a week now and this program gives me an error in add method. I can't find out why?

int a[][]= {{211,21,32,34},{20,21}};
int b[][]={{31,42},{45,21}};

public static void add(int x[][], int y[][]){
    int ar=0,al=0,i=0;

    if(x.length>=y.length) {
        ar=x.length;
    } else {
        ar=y.length;
    }
    if(x[i].length>=y[i].length) {
        al=x[i].length;
    } else {
        al=y[i].length;
    }
    int s[][] = new int[ar][al];
    for(i=0; i<ar; i++) {
        for(int j=0; j<al; j++) {
            s[i][j]=x[i][j]+y[i][j];
        }
        for(i=0; i<ar; i++) {   
            for(int j=0; j<al; j++) {
                System.out.print(s[i][j]+" ");
            }
            System.out.print("\n");
        }
    }
}
armatita
  • 12,825
  • 8
  • 48
  • 49

1 Answers1

0

The problem is in this code:

if(x.length>=y.length) //!!PROBLEM!!
{
    ar=x.length;
}
else{
    ar=y.length;
}
if(x[i].length>=y[i].length) //!!PROBLEM!!
{   al=x[i].length;

}
else{
    al=y[i].length;
}

You're taking the larger of the sizes between these two matrices, which means that whichever one is smaller will throw ArrayIndexOutOfBoundsExceptions whenever you try to index the larger rows/columns.

The logic should be flipped; take the minimum of these lengths:

if(x.length <= y.length) //FIXED
{
    ar=x.length;
}
else{
    ar=y.length;
}
if(x[i].length <= y[i].length) //FIXED
{
    al=x[i].length;
}
else{
    al=y[i].length;
}
Xirema
  • 19,889
  • 4
  • 32
  • 68