user4451270
user4451270

Reputation:

matrix operations with 1-D arrays

Here are two methods that would multiply two 1-D arrays, each holding five integers, and display the resulting 2-D (5x5) array. Unfortunately, I don't get the result I'm hoping for as I get an ArrayIndexOutOfBoundsException. I went over my code to look for the bug but can't seem to find the error. The error message also tells me that the error occurs at the mult[i][j] = array1[i]*array2[j]; statement.

public static int [][]  matrixMult(int [] array1, int [] array2){

    int [][] mult = new int [imax][jmax];
    int i = 0;
    int j = 0;

    while(i < imax){
        while(j < jmax){

            mult[i][j] = array1[i]*array2[j];

            if(j == jmax-1){

                i++;
                j = 0;

            }else{

                j++;
            }
        }
    }

    return mult;
}

public static void print2DArray(int array[][]){

    int i = 0;
    int j = 0;

    while(i < imax){
        while(j < jmax){

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

            if(j == jmax-1){

                i++;
                j = 0;

            }else{

                j++;
            }

        }
    }
}

Upvotes: 0

Views: 31

Answers (1)

Jie Heng
Jie Heng

Reputation: 216

You should break the inner loop when j == jmax-1, otherwise in the next iteration i will become 5 which will give you ArrayIndexOutOfBoundsException.

if(j == jmax-1){
    i++;
    j = 0;
    break; //exit the inner loop
}else{
    j++;
}

Upvotes: 1

Related Questions