简体   繁体   中英

How would i iterate over a 2d array of varying size in Java?

I'm currently creating a brickbreaker (or breakout, like atari breakout) and for the bricks im using a 2d array:

private Brick bricks[][] = new Brick[10][41];

To destroy a specific Brick (for whatever reason i have to destroy that), i created a method:

public void destroyBrick(Brick brick) {
    for(int x = 0; x < bricks[x].length; x++) {
        for(int y = 0; y < bricks[y].length; y++) {
            if (bricks[x][y].equals(brick)) {
                bricks[x][y] = null;
            }
        }
    }
}

The way the array is created is the following:

for(int j=0; j<bricks[0].length; j++){ 
  for(int i=0; i<bricks.length; i++){ 
    bricks[i][j]=new Brick(game,10,Color.GREEN,j*margin,i*margin); 
  }
}

Now for some reason the counter for x eventually reaches 10 and the counter for y reaches 0 where it crashes, and i can't figure out why.

Is there a different way of iterating a 2d array that has different values for columns and rows?

note The reason the formatting and my spelling is so rubbish is, that im writing this on the app version. Feel free to correct any mistakes or formatting errors, before i can.

You are referencing y in the loop that iterates on it. This compiles correctly, because y is defined at the point of reference, but it does not do what you need. In addition, the outer loop should stop upon reaching bricks.length , not bricks[x].length .

These two lines

for(int x = 0; x < bricks[x].length; x++) {
    for(int y = 0; y < bricks[y].length; y++) {

should be

for(int x = 0; x < bricks.length; x++) {
//                       ^
    for(int y = 0; y < bricks[x].length; y++) {
    //                        ^

The first int x doesn't refer to what you need, I think. x ranges from 0 to the length of the array indexed with x, that is 41.

for (int x = 0; x < bricks.length; x++)
    for (int y = 0; y < bricks[x].length; y++)

Should work (at least I wrote this without testing)

Try iterating with any of this

public void destroyBrick(Brick brick) {
    for(int x = 0; x < bricks.length; x++) {
        for(int y = 0; y < bricks[0].length; y++) {
            if (bricks[x][y].equals(brick)) {
                bricks[x][y] = null;
            }
        }
    }
}

or

public void destroyBrick(Brick brick) {
    for(int x = 0; x < bricks.length; x++) {
        for(int y = 0; y < bricks[x].length; y++) {
            if (bricks[x][y].equals(brick)) {
                bricks[x][y] = null;
            }
        }
    }
}

if there's any other error, use your debugger to find out where exactly

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