Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplification of successive 'if' statements in Java [duplicate]

I have a series of if statements, as shown below:

if (board[x+1][y]==true) {
    ar+=1;
}
if (board[x][y+1]==true) {
    ar+=1;
}
if (board[x-1][y]==true) {
    ar+=1;
}
if (board[x][y-1]==true) {
    ar+=1;
}
if (board[x+1][y+1]==true) {
    ar+=1;
}
if (board[x+1][y-1]==true) {
    ar+=1;
}
if (board[x-1][y+1]==true) {
    ar+=1;
}
if (board[x-1][y-1]==true) {
    ar+=1;
}

Is there a way to simplify/condense these statements with Java?

like image 514
Eragon20 Avatar asked Nov 28 '16 04:11

Eragon20


1 Answers

Simply loop around the position that you care about. Skipping the center of the "box".

Tip: You access a 2D array by row then column, or [y][x] (at least, that's how you'd translate the board from looking at the code).

// int x, y;  // position to look around 
for (int xDiff = -1; xDiff <= 1; xDiff++) {
    for (int yDiff = -1; yDiff <= 1; yDiff++) {
        if (xDiff == 0 && yDiff == 0) continue;
        if (board[y+yDiff][x+xDiff]) { 
            ar += 1;
        }
    }
}

Beware - Out of bounds exception is not handled

like image 156
OneCricketeer Avatar answered Oct 12 '22 23:10

OneCricketeer