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

标签 java arrays

所以我有这个方法:

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/

相关文章:

java - Java 中不同的可选/选项语义

java - 如何在 Windows XP 中使用 Java 远程连接 ODBC?

java - Android 蓝牙套接字 IOException : 'read failed, socket might be closed or timeout'

ruby-on-rails - ActiveRecord 关系的排序问题

java - Spring Boot Security 不会抛出 401 Unauthorized Exception 但 404 Not Found

java - java中如何避免反斜杠

java - 如何在 Java 中从 MQ 系列死信的有效负载 (byte[]) 中分离 RFH2(字符串)?

javascript - 在 react 中使用 splice 添加到数组的正确方法是什么

javascript - 如何获取java代码 - String.getBytes ("UTF-8"); JavaScript 中的类似输出

arrays - 用户窗体变量范围 : transfer 2D array values from userform2 to userform1