如何缩小所有这些if语句?

时间:2018-12-08 22:58:46

标签: java if-statement conditional simplify

这部分代码来自学校作业。我可以使用它,但是我觉得我可以简化它,或者至少使它看起来更干净。但是,我尚未能够这样做。有什么建议么? (摘自井字游戏)

if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] != '-') {
    winner = board[0][0];
} else if (board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0] != '-') {
    winner = board[1][0];
} else if (board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0] != '-') {
    winner = board[2][0];
} else if (board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0] != '-') {
    winner = board[0][0];
} else if (board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] != '-') {
    winner = board[0][1];
} else if (board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2] != '-') {
    winner = board[0][2];
} else if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[2][0] != '-') {
    winner = board[2][0];
} else if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '-') {
    winner = board[0][0];
}

3 个答案:

答案 0 :(得分:0)

尝试

 if(check(board[0][0],board[0][1],board[0][2]) &&  board[0][2]!='-')
 .....


private boolean check(a,b,c){
    return a==b && b==c;
}

您还可以看到更好的solution here

答案 1 :(得分:0)

这是另一种方法:

int[][] checks = {{0,0,0,1},{1,0,0,1},{2,0,0,1}, // horizontals
                  {0,0,1,0},{0,1,1,0},{0,2,1,0}, // verticals
                  {0,0,1,1},{2,0,-1,1}};         // diagonals
char winner = '-';
for (int[] check : checks)
    if ((winner = checkWinner(board, check[0], check[1], check[2], check[3])) != '-')
        break;
private static char checkWinner(char[][] board, int y, int x, int dy, int dx) {
    char c = board[y][x];
    return (board[y + dy][x + dx] == c && board[y + dy * 2][x + dx * 2] == c ? c : '-');
}

答案 2 :(得分:0)

接下来的方法呢?如我所见,您的获胜者数量有限:board[0][0]board[1][0]board[2][0]board[0][1]board[2][0]。您可以使用适当的名称为每个Winnger创建单独的Predicate

Predicate<char[][]> isZeroOneWinner = new Predicate<char[][]>() {
    @Override
    public boolean test(char[][] board) {
        return board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] != '-';
    }
};

我认为最好是多个if...else