4

私の質問はboolean isLive = false;、なぜこれが false として割り当てられているのですか? 私は非常に類似した例を見てきましたが、それを理解することは決してありません. 誰かがこの行が何をしているのか説明できますか?

/**
 * Method that counts the number of live cells around a specified cell

 * @param board 2D array of booleans representing the live and dead cells

 * @param row The specific row of the cell in question

 * @param col The specific col of the cell in question

 * @returns The number of live cells around the cell in question

 */

public static int countNeighbours(boolean[][] board, int row, int col)
{
    int count = 0;

    for (int i = row-1; i <= row+1; i++) {
        for (int j = col-1; j <= col+1; j++) {

            // Check all cells around (not including) row and col
            if (i != row || j != col) {
                if (checkIfLive(board, i, j) == LIVE) {
                    count++;
                }
            }
        }
    }

    return count;
}

/**
 * Returns if a given cell is live or dead and checks whether it is on the board
 * 
 * @param board 2D array of booleans representing the live and dead cells
 * @param row The specific row of the cell in question
 * @param col The specific col of the cell in question
 * 
 * @returns Returns true if the specified cell is true and on the board, otherwise false
 */
private static boolean checkIfLive (boolean[][] board, int row, int col) {
    boolean isLive = false;

    int lastRow = board.length-1;
    int lastCol = board[0].length-1;

    if ((row >= 0 && row <= lastRow) && (col >= 0 && col <= lastCol)) {             
        isLive = board[row][col];
    }

    return isLive;
}
4

4 に答える 4

4

ifこれは単なるデフォルト値であり、 test (句) が検証された場合に変更される可能性があります。

ボードの外側のセルはライブではないという規則を定義します。

これは、次のように記述できます。

private static boolean checkIfLive (boolean[][] board, int row, int col) {

    int lastRow = board.length-1;
    int lastCol = board[0].length-1;

    if ((row >= 0 && row <= lastRow) && (col >= 0 && col <= lastCol)) {             
        return board[row][col];
    } else {
        return false;
    }
}
于 2012-10-12T10:11:50.297 に答える
1

最初にブール値を「false」として割り当てます(デフォルトの条件を保証します)
次に、有効な条件が見つかった場合は値を変更し、そうでない場合はデフォルトのfalseが返されます。

于 2012-10-12T10:12:41.003 に答える
1
boolean isLive = false;

これはブール変数のデフォルト値です。インスタンス変数として宣言すると、自動的にfalseに初期化されます。

なぜこれがfalseとして割り当てられるのですか?

さて、これを行うには、デフォルト値から始めて、後でtrue特定の条件に基づいて値に変更できます。

if ((row >= 0 && row <= lastRow) && (col >= 0 && col <= lastCol)) {             
    isLive = board[row][col];
}
return isLive;

したがって、上記のコードでは、if条件がfalseの場合、値を返すのと似ていfalseます。なぜなら、変数isLiveは変更されないからです。

ただし、条件がtrueの場合、return valueはの値に依存しますboard[row][col]。の場合false、戻り値は引き続きfalse、それ以外の場合はtrue

于 2012-10-12T10:13:17.487 に答える
1
boolean isLive = false;

これは、ブール変数に割り当てられたデフォルト値です。

と同じように:

int num = 0;
于 2012-10-12T10:13:51.093 に答える