康威的生命游戏

时间:2012-10-12 10:09:46

标签: java

我的问题是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 个答案:

答案 0 :(得分:4)

这只是默认值,如果验证了测试(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;
    }
}

答案 1 :(得分:1)

首先我们将布尔值指定为'false'(确保默认条件)
然后,如果找到有效条件,我们更改值,否则将返回默认值false。

答案 2 :(得分:1)

boolean isLive = false;

这是布尔变量的默认值。如果将其声明为实例变量,则会自动将其初始化为false。

  

为什么这被指定为假?

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

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

因此,在上面的代码中,如果您的if条件为false,则类似于返回false值。因为,变量isLive未更改。

但如果您的条件为真,那么return value将取决于board[row][col]的值。如果是false,则返回值仍为false,否则为true

答案 3 :(得分:1)

boolean isLive = false;

这是分配给布尔变量的默认值。

就像:

int num = 0;