为了账号安全,请及时绑定邮箱和手机立即绑定

如何将此代码转换为 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 关注
  • 100 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信