我想知道如何将此代码放入 switch 语句中我想在 switch 语句中执行此 if else 语句,请帮助我找出如何将此代码更改为 switch 语句。if (board[r - 1][c] == ' ' && board[r][c - 1] == ' ') { nextRow = r; nextCol = c - 1;`enter code here` return true; } // We will try to move the cell up. if (board[r - 1][c] == ' ') { nextRow = r - 1; nextCol = c; return true; } // We will try to move the cell to the right. else if (board[r][c + 1] == ' ') { nextRow = r; nextCol = c + 1; return true; } // We will try to move the cell to the left. else if (board[r][c - 1] == ' ') { nextRow = r; nextCol = c - 1; return true; } // We will try to move the cell down. else if (board[r + 1][c] == ' ') { nextRow = r + 1; nextCol = c; return true; } System.out.println("Error due to Array Bound Index"); return false; }
3 回答
慕妹3242003
TA贡献1824条经验 获得超6个赞
您无法将其转换为开关,因为您不是根据单个值来选择要执行的操作,并且您的条件并不相互排斥。
但是,您可以将四个 if 转换为循环:
for (int a = 0; a < 4; ++a) {
int dr = (a & 1 == 0) ? 0 : (a & 2 == 0) ? 1 : -1;
int dc = (a & 2 == 0) ? 0 : (a & 1 == 0) ? 1 : -1;
if (board[r + dr][c + dc] == ' ') {
nextRow = r + dr;
nextCol = c + dc;
return true;
}
}
DIEA
TA贡献1820条经验 获得超2个赞
您不能将此转换为 switch 语句,因为您不检查一个值。对于 switch 语句,代码必须如下所示:
int a = 0;
if (a == 0) {
...
}
else if (a == 1) {
...
}
else if (a == 2) {
...
}
...
和 switch 语句:
switch (a) {
case 0:
...
break;
case 1:
...
break;
case 2:
...
break;
}
添加回答
举报
0/150
提交
取消