java二维数组索引_java – 为什么二维数组中的对象的索引返回-1?

所以我有这个方法:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值