康威生命游戏

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

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

所以 return isLive; 返回 false? - user1721548
如果单元格在棋盘外(即测试未经验证),则isLive不会改变,因此返回false。 - Denys Séguret
如果细胞是活的,No. isLive = board[row][col] 会将 isLive 更改为 true。 - mcalex

1
boolean isLive = false;

这是布尔变量的默认值。如果您将其声明为实例变量,则会自动初始化为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


1
boolean isLive = false;

這是賦予布林變數的預設值。

就像:

int num = 0;

@SohelKhalifa,没问题。小错误难免,早点纠正总是好的。 - Rohit Jain

1

首先,我们将布尔值分配为“假”(确保默认条件)
然后,如果发现有效条件,我们更改该值,否则将返回默认的false。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接