-1

This method is meant to find any cell that is matching two aligned cells and store them in a temporary matrix. However whenever I run the program, I get an out of bounds error. The matrix is 3x3. How can I make it stores any 3 matching adjacent cells in the tempMatrix.

public void matchMatrix(){

    int[][] tempMatrix = new int[rowsN][columnsM];
    
    for(int i = 0; i < matrixArr.length; i++){
        
        for(int j = 0; j < matrixArr.length; j++){
            
            if((matrixArr[i][j] == matrixArr[i + 1][j] && matrixArr[i][j] == matrixArr[i + 2][j]) || (matrixArr[i][j] == matrixArr[i][j + 1] && matrixArr[i][j] == matrixArr[i][j + 2])){
                tempMatrix[i][j] = matrixArr[i][j];
            }
        
        }
        
    }
    
    for(int i = 0; i < matrixArr.length; i++){
        
        for(int j = 0; j < matrixArr.length; j++){
            
            if(matrixArr[i][j] == tempMatrix[i][j]) System.out.println("[ ] ");
            else{
            System.out.print("[" + matrixArr[i][j] + "] ");
            }
        }
            System.out.println();
    }
        System.out.println();
}

1 Answers1

0
matrixArr[i][j + 1]

The above code will access outside the last index of the 2D array during the last execution of the inner loop.

    matrixArr[i + 1][j]

The above code will access outside the last index of the 2D array during the last execution of the outer loop.

Also, the code assumes that the 2D array is always a square matrix. j < matrixArr.length but initializes the tempMatrix as tempMatrix = new int[rowsN][columnsM];. This can also exception.

How to fix out of bounds exception

Add explicit checks for boundary conditions

  1. whenever i + 2 is accessed ensure that the current index is atleast 2 lesser than last index
        if (i < matrixArr.length - 2 && j < matrixArr[i].length - 2) {
            if ((matrixArr[i][j] == matrixArr[i + 1][j] && matrixArr[i][j] == matrixArr[i + 2][j])
                || (matrixArr[i][j] == matrixArr[i][j + 1] && matrixArr[i][j] == matrixArr[i][j + 2])) {
            }
        } else if (i < matrixArr.length - 2) {
            if (matrixArr[i][j] == matrixArr[i + 1][j] && matrixArr[i][j] == matrixArr[i + 2][j]) {
            }
        } else if (j < matrixArr[i].length - 2) {
            if (matrixArr[i][j] == matrixArr[i][j + 1] && matrixArr[i][j] == matrixArr[i][j + 2]) {
            }
        }

Horse
  • 2,295
  • 1
  • 2
  • 10