0

So I'm building a sort of "Game of Life" application in java and are having some trouble detecting when the index is out of bounds.The code below is a modified version from another qustion here from SO.

2D array:

1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1

Code

private void traverse() {       
        for (int i = 0; i < brickArray.length; i++) {
            for (int j = 0; j < brickArray[i].length; j++) {

                System.out.println(i - 1 + "," + j);
                checkIfAllowed(i - 1, j);

            }
        }   
    }

    public void checkIfAllowed(int row, int column) {
    boolean incorrect = check(row) && check(column);
    if (incorrect) {
        System.out.println("Wall");
    } else {
        System.out.println("Road");

    }
}

private boolean check(int index) {
    return (index < 0 || index > board.getHeight());
}

Result:

Traversing:

-1,0
Road
-1,1
Road
-1,2
Road
-1,3
Road
0,0
Road
0,1
Road
0,2
Road
0,3
Road
1,0
Road
1,1
Road
1,2
Road
1,3
Road
2,0
Road
2,1
Road
2,2
Road
2,3
Road

In this example, the 4 top cells should have printed "Wall", but they didn't.

protof
  • 1
  • 1
  • `check` in this case seems to imply **incorrect** instead of **correct** – C.B. Nov 10 '16 at 15:07
  • `return (index < 1 || index > board.getHeight());` You realize the `0` is less than `1`, right? – bradimus Nov 10 '16 at 15:08
  • Where do you define `board` and its method `getHeight()`? – Dez Nov 10 '16 at 15:09
  • your check method returns true if the index is out of bounds. So for the case check(0) && check(0) it will return true For any other case it will return false as only true && true == true. false&&true == false, false&&false = false – user3488765 Nov 10 '16 at 15:10
  • change the return value from `check( )` like this: `return index < 0 || index >= board.getHeight( );` – denvercoder9 Nov 10 '16 at 15:12
  • I tried these changes, they work fine for valid input, but not invalid. I have edited my question with some of the comments here. – protof Nov 10 '16 at 15:15

1 Answers1

0

The pitfall of negative names, and neutral names (check).

boolean incorrect = check(row) || check(column);

When either row or column is incorrect, the whole coordinates are incorrect.

I would write check out here, also as now the board must be square using getHeight in check.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138