I am making a chess program in Java. I have a boolean method that takes the location that the user would like to move a rook to, in the form of two int
s, and based on the rook's current row and column, determines if the rook can move there, using for loops. Here is one of the loops as an example.
int nc = col - 1;
while (nc >= 0){
moves.add(new Integer[]{row, nc});
if (locals[row][nc] != null)
break;
nc--;
}
moves
is an ArrayList that I have declared earlier in the program. It stores a list of all the valid moves, and this is one of the for loops I use to instantiate it.
The issue is, each time I run this code, the lines that include the add methods are highlighted for being infinite loops, and the code will not run. What am I doing wrong?
Edit:
This is the exact error message that the software is showing me:
Additionally, I'm going to post the full text of the method. I'm not sure if any of it is relevant to my question, but it might prove helpful.
public boolean isValidMove(int r, int c){
Piece[][] locals = Chess.getBoard();
if (r < 0 || c < 0 || r > 7 || c > 7 || (locals[r][c] != null && locals[r][c].getWhite() == isWhite))
return false;
ArrayList<Integer[]> moves = new ArrayList<Integer[]>();
int nc = col - 1;
while (nc >= 0){
moves.add(new Integer[]{row, nc});
if (locals[row][nc] != null)
break;
nc--;
}
nc = col + 1;
while (nc < 8){
moves.add(new Integer[]{row, nc});
if (locals[row][nc] != null)
break;
nc++;
}
int nr = row - 1;
while (nr >= 0){
moves.add(new Integer[]{nr, col});
if (locals[nr][col] != null)
break;
nr--;
}
nr = row + 1;
while (nr < 8){
moves.add(new Integer[]{nr, col});
if (locals[nr][col] != null)
break;
nr++;
}
for (Integer[] ints : moves){
if (ints[0] == r && ints[1] == c)
return true;
}
return false;
}
I discovered what is wrong the program and managed to fix it. The loop in question does not in fact iterate forever, however a method somewhere in this program called another method which in turn called the original method. Hence, the Stack Overflow error without any one infinitely recursive method.