java布尔方法的行为不符合预期,当预期为true时返回false
下面是有问题的代码:
public boolean validMoveRook(int[] start, int[] end) {
int xDif = end[0]-start[0];
int yDif = end[1]-start[1];
if (xDif == 0 ^ yDif == 0) {
int distance;
int direction;
if (xDif == 0) {
distance = Math.abs(yDif);
direction = 1;
}
else {
distance = Math.abs(xDif);
direction = 0;
}
for (int i = distance - 1; i >= 0; i--) {
if (direction == 0) {
int newX = start[0] + utilities.AbsoluteChange(xDif, -i);
if (this.board[newX][start[1]] != FREE) return false;
}
if (direction == 1) {
int newY = start[1] + utilities.AbsoluteChange(yDif, -i);
if (this.board[start[0]][newY] != FREE) return false;
}
if (this.board[start[0]][start[1]] == TURN0_WHITEROOK) {
this.board[start[0]][start[1]] = WHITEROOK;
}
if (this.board[start[0]][start[1]] == TURN0_BLACKROOK) {
this.board[start[0]][start[1]] = BLACKROOK;
}
}
System.out.println("success");
return true;
}
System.out.println("Oh no!");
return false;
}
我想下一盘棋。问题是,即使在不应该返回false的时候,它仍然返回false。打印“success”时,它仍然返回false。为什么会这样
# 1 楼答案
正如@Gblodgett所指出的,很可能在
utilities.AbsoluteChange
方法中有一个Sop("success")
,并且false
就在调用之后返回