4

我的问题是boolean isLive = 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

这只是默认值,如果 test (if子句) 被验证,它可能会被更改。

它定义了板外单元不活动的约定。

这可以写成:

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。

为什么这被分配为假?

好吧,我们这样做,只是从默认值开始,然后我们可以稍后true根据特定条件更改为值。

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

所以,在上面的代码中,如果你的if条件为假,那么它类似于返回一个false值。因为,变量isLive没有改变。

但是,如果您的条件为真,那么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 回答