不使用开关避免重复的if语句?

时间:2018-01-10 16:47:10

标签: java if-statement switch-statement

我正在为学校项目制作tic tac toe并创建了一个名为checkWin(char [] [] board)的方法,该方法检查每个答案组合以查看是否有获奖板。这在每个回合之后运行并且完美地运行,但是总共16个if语句,每个潜在的胜利组合一个。因为我正在检查不同数组元素的组合,所以我不能使用交换机,但有没有其他方法可以避免大量重复的switch语句?

1 个答案:

答案 0 :(得分:1)

我使用某种对象数组。

以下是针对每个点使用int[2]的简化版本,但您应该使用Point类和xy坐标。这应该证明了使用数据结构是多么容易。

// The point coordinates of each point in each possible winning line.
static final int[][][] LINES = {
        {{0, 0}, {0, 1}, {0, 2}},
        {{1, 0}, {1, 1}, {1, 2}},
        {{2, 0}, {2, 1}, {2, 2}},
        {{0, 0}, {1, 0}, {2, 0}},
        {{0, 1}, {1, 1}, {2, 1}},
        {{0, 2}, {1, 2}, {2, 2}},
        {{0, 0}, {1, 1}, {2, 2}},
        {{2, 0}, {1, 1}, {0, 2}},
};
// The players.
static final int PLAYER1 = 1;
static final int PLAYER2 = -1;

private int checkWin(int[][] board) {
    // Check each line.
    for (int[][] line : LINES) {
        // Add up the total value of each line.
        int total = 0;
        for (int[] point : line) {
            // Use the point to specify which square on the board to check.
            total += board[point[0]][point[1]];
        }
        // If the total adds up to 3 or -3 then someone has won on this line.
        if (total == line.length * PLAYER1) {
            return PLAYER1;
        }
        if (total == line.length * PLAYER2) {
            return PLAYER2;
        }
    }
    // Nobody won.
    return 0;
}

public void test(String[] args) {
    int[][] board = new int[3][];
    for ( int i = 0; i < board.length; i++) {
        board[i] = new int[3];
    }
    // Set up a win..
    board[0][0] = PLAYER1;
    board[1][1] = PLAYER1;
    board[2][2] = PLAYER1;
    int winner = checkWin(board);
    System.out.println(winner);
}