简体   繁体   中英

Array index out of bounds exception -1

I have this assignment due within 40 minutes from now... I submit it to this online thing and it tests the methods etc and I'm getting this error. I know what out of bounds is, but I don't understand where it is occurring in the code it specifies:

public int countNeighbours(int x, int y) {
    int neighbourCount = 0;


    for (int i = 0; i < cells.length; i++) {
        for (int j = 0; j < cells.length; j++) {

            if ((cells[x][y].isAlive() == true) && (x < cells.length) && (y < cells.length) && (x >= 0)
                    && (y >= 0)) {

                neighbourCount++;
            }

            else if ((cells[x][y].isAlive() == false) && (x < cells.length) && (y < cells.length) && (x >= 0)
                    && (y >= 0)) {
                neighbourCount--;
            }

            else if (!(x < cells.length) || !(y < cells.length) || !(x >= 0) || !(y >= 0)) {
                return 0;
            }

            else {
                neighbourCount = neighbourCount;
            }

        }
    }
    return neighbourCount;
}

I don't know if it actually even works, I had a different code for this, but had issues with it.

Anyway, the online thing basically tests for an invalid coordinate and makes sure my code returns the correct value for an invalid coordinate (ie returns 0).

So I don't know why there is an out of bounds error, I feel like I have specified the bounds completely.

I also have a sub question, it also fails a test where the cell has 8 neighbours but my code returns -9. So obviously it's only going through the one which returns neighbourCount-- but I really don't understand why. Have I missed something in the specifications? Or perhaps it's related to a completely different part of my code.

Expressions are evaluated from left to right, so you should check the values of x and y are inside the valid range before accessing cell[x][y] :

if ((x < cells.length) && (y < cells.length) && (x >= 0)
                && (y >= 0) && (cells[x][y].isAlive() == true)) 

BTW, this test assumes that cells is a square matrix (ie it has the same number of columns and rows).

PS, it's unclear why you iterate over i and j and then don't use them at all inside your loops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM