I am writing a small program of how to calculate sum of neighbours of a given position in a grid. for some reason the program does not recognize the right value as correct. I was wondering if that may be because i am using try catch to restrict out of bounds or if it something else i have missed?
i am using a simple 3x3 grid numbered 1 - 9. i have used the same matrix for many other tests so assume there is nothing wrong with the grid. This even though i get 11 when debugging and checking step by step. i dont quite understand, does anyone have an idea?
the -1 in sum was simply to force it to 11 (2+4+5) but the program still yields false when running the input positions. either there is something ive missed or something i have not understood
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
out.println(sumNeighbours(matrix, 0, 0) == 11);
int sumNeighbours(int[][] matrix, int row, int col) {
int sum = -1;
try {
for (int i = row - 1; i <= row; i++) {
for (int j = col - 1; j <= col; j++) {
sum = sum + matrix[i][j];
}
}
} catch (ArrayIndexOutOfBoundsException e) {
} return sum;