我在我的项目中遇到了与邻居有关的问题,我必须修改两种不同的方法来进行康沃尔的生活游戏。我的TA说我的代码看起来应该可以工作但是neightbor计数不起作用。我已经打印了neightbor代码并且它第一次工作,而不是在剩下的运行中只到0。任何人都知道我搞砸了什么?
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
答案 0 :(得分:1)
您在此循环中的条件中使用了错误的变量:
for (int j = colIndex-1; j<=rowIndex+1; j++) {
应该是:
for (int j = colIndex-1; j<=colIndex+1; j++) {