我有这个方法:
public static int[][] executeRules(int[][] array){
int rowNumber = 0;
for(int[] row : array){
for (int cell:row){
int index = Arrays.asList(array).indexOf(cell);
System.out.println(index);
int[] surroundingCells = getSurroundingCells(index);
int liveCells = 0;
for(int aSurroundingCell: surroundingCells){
if(aSurroundingCell == 1){
liveCells++;
}
}
//If cell is dead
if (cell == 0){
//Bring cell back to life if condition is met (three surrounding cells alive)
if (liveCells == 3){
cell = 1;
liveCells = 0;
}
}
//If cell is alive
else if (cell == 1){
//If cell is underpopulated
if (liveCells < 2){
cell = 0;
}
if (liveCells > 3){
cell = 1;
}
}else {
System.out.println("An error has occured.");
}
if(index != -1){
array [rowNumber][index] = cell;
}
}
if(rowNumber < _size - 1){
rowNumber ++;
}
}
return array;
}
这是康威生命游戏,我试图测试这个二维数组中的每个“单元格”,然后更改其值并返回新的数组。但由于某种原因,第二维的索引总是返回-1。我不知道为什么。有人知道吗?
indexOf
将返回 -1。 - Hot LicksindexOf
而不是传统的for
循环有点愚蠢。 - Hot LicksList
里有array
而不是值,因为你传递了一个int[][]
,所以你有一个int[]
列表。 - Dima MaliginindexOf
没有任何机会能够工作。 - Hot LicksArrays.asList(array)
应该改为Arrays.asList(row)
- 你应该将它发布为一个答案! - Nir Alfasi