Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get all neighbors of cell in array without out of bounds exception

I’m trying to make an ArrayList out of all the cells that neighbor a given cell in an array. Currently, my code works for any cell that does not have neighbors in the last row or right-most column. If it does have neighbors in these, I get the error message: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3"

Here’s my code:

public ArrayList<Cell> getNeighbors(int row, int col) {
        ArrayList<Cell> neighbors = new ArrayList<Cell>();
        for (int r = row - 1; r <= row + 1; r++) {
            for (int c = col - 1; c <= col + 1; c++) {
                if (!(r == row && c == col)) {
                    if ((c >= 0 && r >= 0) && (c <= (col + 1) && r <= (row + 1))) {
                        neighbors.add(landscape[r][c]);
                    }
                }
            }
        }
        return neighbors;
    }

Getting the neighbors of cell (1, 1) in a 2×2 grid like this one

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0 0 0

0 0 0

0 1 1

returns: [0, 0, 0, 0, 0, 0, 1, 1] (Works correctly)

but if I look for the neighbors of any cell in row/col 2, I get the error and I don’t know what I’m doing wrong.

Please help!!

>Solution :

Your bounds check is wrong.

c >= 0 && r >= 0 && r < landscape.length && c < landscape[r].length
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading