Anna Anna - 7 days ago 7
Java Question

Find element position array in java

I need to write some methods for a game in java and one of them is int[] findStone. The method returns an array, which gives the coordinate of the element that I am searching.

The field looks like this and is defined like this:

private static int[][] gamefield = new int[8][6];

So if I use the method: findStone(3)[0], it should return 0 for the x coordinate and for findStone(3)1, 2. This is the code that I wrote.

private static int[] findStone(int stone) {

int[] position = new int[2];

for(int x = 0; x < 8; x++ ){
for(int y = 0; y < 6; y++ ) {

int a = gamefield[x][y];
int i = x;
int j = y;

if(a == stone) {
position[0] = i;
position[1] = j;
}
break;
}
}
return position;

}


The problem is: The method only returns the x-coordinates for the first row corectly, for the other elements it shows me 0. Could someone explain me what I did wrong and what I should change? Please, only simple explanation. I am only at the beginning and I don't have experience in java.
Thank you :)

Answer

You probably intended to put your break clause inside the if block. The way you have it now, the break keyword has no effect. It just breaks the inner loop (with y variable), but since this block of code ends here anyway, it simply does nothing.

You're searching for a single point on your map, so when you find the stone position, you can immediately return it, as there's nothing more to do.

Moreover, you don't need additional variables, a, i and j. Using them is not wrong, but code looks clearer and is more concise without them. Have a look at this code:

private static int[] findStone(int stone) {

    int[] position = new int[2];

    for (int x = 0; x < 8; x++) {
        for (int y = 0; y < 6; y++) {

            if (gamefield[x][y] == stone) {
                position[0] = x;
                position[1] = y;

                return position;
            }
        }
    }
    return null; // if there's no given stone
}
Comments