所以我有这个方法:
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。我不知道为什么。有人知道吗?
最佳答案
for(int[] row : array){
for (int cell:row){
int index = Arrays.asList(array).indexOf(cell);
您对行和单元格之间有些混淆。 array
是一个数组数组,所以 indexOf()
将搜索数组值(行),但是您传入的 cell
值是只是一个 int
。它永远找不到等于 int[]
的 int
。
使用 for-each 循环然后尝试通过扫描循环内的值来查找索引有点复杂且效率低下。使用数组索引时,我强烈建议使用传统的 for
循环而不是 for-each 循环。
for(int rowIndex = 0; rowIndex < array.length; rowIndex++) {
int[] row = array[rowIndex];
for(int columnIndex = 0; columnIndex < row.length; columnIndex++) {
int[] surroundingCells = getSurroundingCells(rowIndex, columnIndex);
另外,请注意 Java 处理内存引用的方式,设置变量的值将仅更改该变量。您必须使用数组的索引设置语法来实际更改数组中给定点的值:
int cell = array[rowIndex][columnIndex];
cell = someValue; // This does nothing to your array values.
array[rowIndex][columnIndex] = someValue; // This is what you want.
关于java - 为什么二维数组中对象的索引返回-1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28838517/