我想知道如何將此代碼放入 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
提交
取消