亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將此代碼轉換為 switch 語句

如何將此代碼轉換為 switch 語句

牧羊人nacy 2023-06-21 15:42:38
我想知道如何將此代碼放入 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;

    }

}


查看完整回答
反對 回復 2023-06-21
?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

看來您沒有對每個 if-else 檢查相同的值,因此不可能使用開關進行寫入。switch 語句檢查一個變量以查看它是否適合給定值。


查看完整回答
反對 回復 2023-06-21
?
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;

}


查看完整回答
反對 回復 2023-06-21
  • 3 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號