0

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;
  • yes right now i am adding the cells value itself to the sum, but just for testing i changed sum to sum = -1 (cell 0,0), and the result will be 11 but the line out.println(sumNeighbours(matrix, 0, 0) == 11); still prints false. – Muguwaranojar Jan 09 '22 at 12:54
  • 1
    When `row = 0` then 'row-1 = -1`. The same applies to `col` so the in the first loop you have `matrix[-1][-1]` – c0der Jan 09 '22 at 12:56
  • yes that is correct, but AIOOBE catches that and proceeds, adding nothing the sum. i am though starting to wonder if that might be what causes it to return false. the debugger doesnt seem to argue with it though. – Muguwaranojar Jan 09 '22 at 13:00
  • 1
    Never catch AIOOBE. Set your for loop bounds to avoid AIOOBE. – Hovercraft Full Of Eels Jan 09 '22 at 13:11

3 Answers3

1

Simple printouts (or better: using a debugger ) show you what is happening:

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++) {
                System.out.println("Step 1 invalid indecies: i " + i +" j "+j);
                sum = sum + matrix[i][j];
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Step 2 exiting loop, muted exception");
    }

    System.out.println("Step 3 returning sum "+sum);
    return sum;
}

Side note: exceptions are just that. They are meant to handle exceptional situations. Avoid using exceptions to control your program.

c0der
  • 18,467
  • 6
  • 33
  • 65
1

I'm going to post this here as a community wiki, so as not to detract from cOder's answer (1+ to it, by the way), but the key is to write your code to avoid running into AIOOBE, to create loop start and end values that prevent this from happening, something like:

int sumNeighbours(int[][] matrix, int row, int col) {
    int sum = 0;
    
    int iStart = Math.max(0, row - 1);
    int iEnd = Math.min(matrix.length, row + 2);
    for (int i = iStart; i < iEnd; i++) {
        int jStart = Math.max(0, col -1);
        int jEnd = Math.min(matrix[i].length, col + 2);
        for (int j = jStart; j < jEnd; j++) {
            sum += (i == row && j == col) ? 0 : matrix[i][j];
        }
    }
    return sum;
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

In the first iteration i and j is equal to -1 and you are trying to get value from matrix[-1][-1] and then exception is thrown. Catch block is empty so no operation is done and finally your program returns sum (it is -1).

If you want to continue iteration after exception you should do something like this:

for (int i = row - 1; i <= row; i++) {
    for (int j = col - 1; j <= col; j++) {
        try {
            sum = sum + matrix[i][j];
        }
        catch (Exception e) {
            // do nothing
        }
    }
} return sum;

In this case only adding is in the loop, so error doesn't stop it.

PS: try to avoid handling situations like this with try catches

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Oskar
  • 379
  • 4
  • 21
  • 1
    _try to avoid handling situations like this with try catches_ good advice. Consider posting code that follows this advice – c0der Jan 09 '22 at 13:21
  • Just making works the code from post with describing an issue, cuz author wanted to know why it does not. – Oskar Jan 09 '22 at 13:32