我的问题是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;
}发布于 2012-10-12 18:11:50
这只是缺省值,如果验证了测试(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-12 18:12:41
首先,我们将布尔值指定为'false‘(确保默认条件)
然后,如果找到有效条件,我们将更改该值,否则将返回default false。
发布于 2012-10-12 18:13:17
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是不变的。
但是如果您的条件为真,那么return value将取决于board[row][col]的值。如果为false,则返回值仍为false,否则为true。
https://stackoverflow.com/questions/12856811
复制相似问题