首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >康威的生活游戏

康威的生活游戏
EN

Stack Overflow用户
提问于 2012-10-12 18:09:46
回答 4查看 388关注 0票数 4

我的问题是boolean isLive = false;,为什么这个被赋值为false?我见过非常相似的例子,但我从来没有理解过它。有人能解释一下这行是做什么的吗?

代码语言:javascript
复制
/**
 * 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;
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-10-12 18:11:50

这只是缺省值,如果验证了测试(if子句),则可以更改该值。

它定义了一个约定,即板外的细胞不是活的。

这可以写成:

代码语言:javascript
复制
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;
    }
}
票数 4
EN

Stack Overflow用户

发布于 2012-10-12 18:12:41

首先,我们将布尔值指定为'false‘(确保默认条件)

然后,如果找到有效条件,我们将更改该值,否则将返回default false。

票数 1
EN

Stack Overflow用户

发布于 2012-10-12 18:13:17

代码语言:javascript
复制
boolean isLive = false;

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

为什么这被赋值为false?

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

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12856811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档