缩短Java中的数组

时间:2015-04-06 20:58:39

标签: java arrays

我的部分代码中包含此内容。

public void drawBoard(){
    for (int i = 0; i < 8; i++){
        for (int j = 0; j < 8; j++){
            board[i][j] = null;
        }
    }

    board[0][1] = new Piece(false);
    board[1][1] = new Piece(false);
    board[2][1] = new Piece(false);
    board[3][1] = new Piece(false);
    board[4][1] = new Piece(false);
    board[5][1] = new Piece(false);
    board[6][1] = new Piece(false);
    board[7][1] = new Piece(false);
}

除了逐个声明每个元素的位置之外,有没有办法缩短它?

1 个答案:

答案 0 :(得分:5)

public void drawBoard(){
    for (int i = 0; i < 8; i++){
        for (int j = 0; j < 8; j++){
            board[i][j] = null;

        }
        board[i][1] = new Piece(false);
    }
}

对于踢球,如果你使用一维阵列代表8x8板,你可以用这种方式做同样的事情,消除循环。

public void drawBoard() {
    int j = -1;
    for (int i = 0; i < 64; i++) {
        // j represents your "column"
        // every 8 counts, a new column is found
        if ( i % 8 == 0 ) {
            j++;
        }

        // for the '1' column, set your piece, else null
        board[i] = ( j == 1) ? new Piece(false) : null;
    }
}