Why does the index of an object in a two-dimensional array return -1?

So, I have this method:

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;
}

This is a game of life, yes. I try to check every “cell” in this two-dimensional array, then change its value and then return a new array. But for some reason, the index of the second dimension always returns -1. I have no idea why. Somebody knows?

+4
source share
2 answers
for(int[] row : array){
    for (int cell:row){
        int index = Arrays.asList(array).indexOf(cell);

You get a little confused between your rows and cells. arrayis an array of arrays, so it indexOf()will look for the values ​​of the array (string), but the value cellyou pass is simple int. He can never find an intequal 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.
+2

indexOf ,

list -1,

, .

, asList , , .

asList List<int[]>, List int (cell), .

. .

+2

All Articles