I want to check the 8th positions adjacent to each of the positions of my two-dimensional
array but the firsts ones give me error because there aren't positions there.
How can I avoid that error? The same happened to me in the past and I couldn't solve it neither.
Example image of what I want to do:
Code of my method:
private static void evoluciona(char[][] tauler2, char[][] tauler22) {
for(int i = 0; i < files; i++) {
for(int j = 0; j < columnes; j++) {
tauler2[i][j] = tauler[i][j];
}
}
for(int i = 0; i < files; i++) {
for(int j = 0; j < columnes; j++) {
if(tauler2[i][j] == 'x') {
int cont = 0;
if(tauler2[i-1][j] == '*') {
cont++;
}
if(tauler2[i-1][j-1] == '*') {
cont++;
}
if(tauler2[i-1][j+1] == '*') {
cont++;
}
if(tauler2[i][j-1] == '*') {
cont++;
}
if(tauler2[i+1][j-1] == '*') {
cont++;
}
if(tauler2[i+1][j] == '*') {
cont++;
}
if(tauler2[i+1][j+1] == '*') {
cont++;
}
if(tauler2[i][j+1] == '*') {
cont++;
}
if(cont == 2 || cont == 3) {
tauler2[i][j] = '*';
}
}
else if(tauler2[i][j] == '*') {
int cont = 0;
if(tauler2[i-1][j] == '*') {
cont++;
}
if(tauler2[i-1][j-1] == '*') {
cont++;
}
if(tauler2[i-1][j+1] == '*') {
cont++;
}
if(tauler2[i][j-1] == '*') {
cont++;
}
if(tauler2[i+1][j-1] == '*') {
cont++;
}
if(tauler2[i+1][j] == '*') {
cont++;
}
if(tauler2[i+1][j+1] == '*') {
cont++;
}
if(tauler2[i][j+1] == '*') {
cont++;
}
if(cont == 2 || cont == 3) {
tauler2[i][j] = '*';
}
else {
tauler2[i][j] = 'x';
}
}
}
}
}