我正在用Java编写国际象棋程序。我有一个布尔方法,该方法以两个int
的形式获取用户希望将车子移到的位置,并根据车子的当前行和列确定车子是否可以移动到那里,使用循环。这是一个循环示例。
int nc = col - 1;
while (nc >= 0){
moves.add(new Integer[]{row, nc});
if (locals[row][nc] != null)
break;
nc--;
}
moves
是我先前在程序中声明的ArrayList。它存储所有有效动作的列表,这是我用来实例化它的for循环之一。
问题是,每次我运行此代码时,都会将包含add方法的行突出显示为无限循环,并且该代码将无法运行。我在做什么错?
编辑:
这是软件显示给我的确切错误消息:
此外,我将发布该方法的全文。我不确定是否与我的问题有关,但可能会有所帮助。
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;
}
我已将代码制作为Meal Ready to Eat,并且看起来工作正常。
问题似乎没有出现在问题中。如果while
主体周围没有括号,则if
可能会引起上述问题。我强烈建议始终将括号括起来,即使这是多余的输入。
interface Inf {
static void main(String[] args) {
int row = 2;
int col = 2;
Integer[][] locals = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
java.util.List<Integer[]> moves = new java.util.ArrayList<>();
int nc = col - 1;
while (nc >= 0){
moves.add(new Integer[]{row, nc});
if (locals[row][nc] != null)
break;
nc--;
}
}
}