2015-10-31 58 views
-2

我現在正在與我的項目中的鄰居問題,我必須修改康威生活遊戲的兩種不同方法。我的TA說我的代碼看起來應該可以工作,但是neighbor計數不起作用。我一直在打印neightbor代碼,並且它第一次運行,而不是在剩下的運行時只是0。任何人有一個想法,我在哪裏搞亂?康威的生活遊戲鄰居問題(java)

public static void updateLife(Boolean[][] gameCellAlive) { 
int size = gameCellAlive.length; 
System.out.println("size of temp--->"+size); 
Boolean[][] tempCell = new Boolean [size][size]; 
int row = 0; 
int col = 0; 
for (row = 0; row<tempCell.length; row++) { 
for(col=0; col<tempCell[0].length; col++) { 
tempCell[row][col] = gameCellAlive[row][col]; 
} 
} 
for (int i = 0; i<tempCell.length; i++) { 
for (int j = 0; j<tempCell[0].length; j++) { 
int tempInt = getLifeNeighborCount(gameCellAlive, j, i); 
System.out.println("neighbors---->"+tempInt); 
if ((tempInt>3) || (tempInt<2)) { 
tempCell[i][j] = false; 
} 
else if(tempInt == 3) { 
tempCell[i][j] = true; 
} 
else if(tempInt==2) { 
tempCell[i][j]=true; 
} 
/*else { 
tempCell[row][col]=gameCellAlive[row][col]; 
}*/ 

}//2nd for loop 
}//for loop 

for (int x = 0; x<tempCell.length; x++) { 
for(int y=0; y<tempCell[0].length; y++) { 
gameCellAlive[x][y] = tempCell[x][y]; 
} 
} 

    // METHOD STUB - This method needs to be implemented! 
//if statemeent for requirements. 
} // end method updateLife 

/** 
* 
* @param gameBoard A 2D boolean array containing the current life status of 
* each cell at each x,y coordinate on the board. true indicates that the 
* cell is alive. false indicates no life in that cell. 
* @param colIndex The x position of the cell in the game board whose 
* neighbors are to be counted. 
* @param rowIndex The y position of the cell in the game board whose 
* neighbors are to be counted. 
* @return the number of cells adjacent to the cell at the specified row and 
* column that contain life. This value ranges between 0 (no adjacent cells 
* contain life) and 8 (all adjacent cells contain life). 
* 
* CS1180 Note: YOU NEED TO IMPLEMENT THIS METHOD 
*/ 
public static int getLifeNeighborCount(Boolean[][] gameBoard, int colIndex, int rowIndex) { 
    // METHOD STUB - THIS METHOD NEEDS TO BE IMPLEMENTED 
    int neighborCount = 0; 

    //check for alive or dead 
    for (int i = rowIndex-1; i<=rowIndex+1; i++) { 
    for (int j = colIndex-1; j<=rowIndex+1; j++) { 
    try { 
    if (gameBoard[i][j]==true && (i !=rowIndex || j!=colIndex)) { 
    //System.out.println("hello"); 
    neighborCount++; 
    }//end if 
    }//end try 

    catch (ArrayIndexOutOfBoundsException e){   
    }//end catch 
    }//end second foor loop 
    }//end first foor loop 
    return neighborCount; 
    }// end method getLifeNeighborCount 
+2

我看不懂你的代碼 - 請提高其格式。 –

+0

每次程序員寫一個空的'catch'子句時,寶寶熊貓都會死...... – GabrielOshiro

+0

每次有人在網上發表一條毫無意義的評論。 –

回答

1

你在這個循環中使用了錯誤的變量條件:

for (int j = colIndex-1; j<=rowIndex+1; j++) { 

它應該是:

for (int j = colIndex-1; j<=colIndex+1; j++) { 
+0

哇不能相信我沒有看到,謝謝 –