如何将此代码转换为 switch 语句

我想知道如何将此代码放入 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;

    }



牧羊人nacy
浏览 139回答 3
3回答

慕妹3242003

您无法将其转换为开关,因为您不是根据单个值来选择要执行的操作,并且您的条件并不相互排斥。但是,您可以将四个 if 转换为循环:for (int a = 0; a < 4; ++a) {&nbsp; &nbsp; int dr = (a & 1 == 0) ? 0 : (a & 2 == 0) ? 1 : -1;&nbsp; &nbsp; int dc = (a & 2 == 0) ? 0 : (a & 1 == 0) ? 1 : -1;&nbsp; &nbsp; if (board[r + dr][c + dc] == ' ') {&nbsp; &nbsp; &nbsp; nextRow = r + dr;&nbsp; &nbsp; &nbsp; nextCol = c + dc;&nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }}

尚方宝剑之说

看来您没有对每个 if-else 检查相同的值,因此不可能使用开关进行写入。switch 语句检查一个变量以查看它是否适合给定值。

DIEA

您不能将此转换为 switch 语句,因为您不检查一个值。对于 switch 语句,代码必须如下所示:int a = 0;if (a == 0) {&nbsp; &nbsp; ...}else if (a == 1) {&nbsp; &nbsp; ...}else if (a == 2) {&nbsp; &nbsp; ...}...和 switch 语句:switch (a) {&nbsp; &nbsp; case 0:&nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case 1:&nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case 2:&nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; break;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java