2012-10-12 48 views
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

這根本的默認值,如果測試(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; 
    } 
} 
+0

所以'返回將isLive;'返回false? – user1721548

+0

是的,如果單元不在板上(即測試未驗證),isLive不會更改,因此它返回false。 –

+0

編號'isLive = board [row] [col]'如果單元格生效,則更改isLive爲真 – mcalex

1

首先我們給布爾值「假」(確保默認條件)
那麼,如果有效的條件是發現我們改變了價值,否則默認爲false會回。

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

1
boolean isLive = false; 

它是分配給布爾變量的默認值。

就像:

int num = 0; 
+0

@SohelKhalifa ..是的,它沒有問題。發生小錯誤。最好早點糾正它們。 –