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

Java 避免重复的if语句而不使用开关?,java,if-statement,switch-statement,Java,If Statement,Switch Statement,我正在为一个学校项目制作tic-tac-toe,并创建了一个名为checkWin(char[][]board)的方法,该方法检查每个答案组合,看看是否有一个获胜的board。这在每个回合后都会运行,效果很好,但总共有16条if语句,每一方的每一个潜在胜利组合对应一条语句。因为我在检查不同数组元素的组合,所以我不能使用switch,但是有没有其他方法可以避免大量重复的switch语句?我会使用某种类型的对象数组 这里是一个简单的版本,对每个点使用int[2],但实际上应该使用带有x和y坐标的poi

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

我会使用某种类型的对象数组

这里是一个简单的版本,对每个点使用
int[2]
,但实际上应该使用带有
x
y
坐标的
point
类。这应该说明使用数据结构是多么容易

// 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);
}
//每条可能获胜线中每个点的点坐标。
静态最终int[][]行={
{{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}},
};
//球员们。
静态最终整数播放器1=1;
静态最终整数PLAYER2=-1;
专用int checkWin(int[]]板){
//检查每一行。
对于(int[][]行:行){
//把每行的总值加起来。
int-total=0;
对于(int[]点:线){
//使用该点指定要检查板上的哪个正方形。
总计+=线路板[点[0]][点[1]];
}
//如果总数加起来是3或-3,那么有人在这条线上赢了。
如果(总计==行长度*播放者1){
返回播放器1;
}
如果(总计==行长度*播放者2){
返回PLAYER2;
}
}
//没有人赢。
返回0;
}
公共无效测试(字符串[]args){
int[][]板=新int[3][];
对于(int i=0;i
显示到目前为止您编写的关于您想要实现的目标的代码