Switch语句做与之相反

时间:2018-11-05 20:02:26

标签: java

我在这里使用了一个案例声明:

  String color = this.getPlayer().getColor();

    System.out.print("\nCOLOR IS: " + color + "\n");

    switch(color) {
        case "Black":
            /*
            we need the front two diag pieces. Are they opposition color?

             */

            Piece p = board[fromX - 1][fromY - 1].getPiece();
            if ((p != null) & (p.getPlayer().getColor() != this.getPlayer().getColor())) {
                if (p instanceof Pawn) {
                    return true;
                }
            }

            p = board[fromX + 1][fromY - 1].getPiece();
            if ((p != null) & (p.getPlayer().getColor() != this.getPlayer().getColor())) {
                if (p instanceof Pawn) {
                    return true;
                }}

        case "White":
            System.out.print("\n\nYOU ARE IN WHITE CASE STATEMENT");



            p = board[fromX - 1][fromY + 1].getPiece();
            if ((p != null) & (p.getPlayer().getColor() != this.getPlayer().getColor())) {
                if (p instanceof Pawn) {
                    return true;
                }
            }

            p = board[fromX + 1][fromY + 1].getPiece();
            if ((p != null) & (p.getPlayer().getColor() != this.getPlayer().getColor())) {
                if (p instanceof Pawn) {
                    return true;
                }
            }}

并运行此代码将使我陷入白色情况,即使String color变量肯定是Black。 这是事实的证明

    COLOR IS: Black


YOU ARE IN WHITE CASE STATEMENTException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
    at King.underThreat(King.java:233)
    at Game.move(Game.java:118)
    at main.main(main.java:19)

Process finished with exit code 1

这意味着this.getPlayer().getColor()绝对是“黑色”,并且在我设置的switch语句中正相反。任何人都可以解释发生这种情况的情况吗?对我来说似乎很不合逻辑。

2 个答案:

答案 0 :(得分:2)

您的代码中永远不会有break

switch (color) {
case "Black":
    // Code
    break;

case "White":
    // Code
    break;
}

答案 1 :(得分:0)

您遇到了这个问题,因为您没有使用break,如果没有使用它,它将涉及所有情况。正确的语法是:

switch(color) {
    case "Black":
    // your code
       break;
    case "White":
    // your code
       break;
}