所以我有这个方法:
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()将搜索数组值(行),但传入的单元格值只是一个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,arrays
来源: https://codeday.me/bug/20190623/1275290.html