Weird Array Bug

Hey guys,

I’m having this really obnoxious bug in a 2d array. Getting array data only works when searching with a positive increment.

Find Grid Code:


	public static Grid getGrid(float x, float y) {
		Grid r = null;
		try {
			r = channels[(int) x][(int) y];
		} catch (ArrayIndexOutOfBoundsException e) {
			r = new Grid();
		}
		return r;
	}

Here is where the problem is:


	public void findNeighbors() {
		if (!found) {
			north = Game.getGrid((int) position.x / 10, (int) (position.y / 10) - 1);// not
																					// working
			east = Game.getGrid((int) position.x / 10 + 1, (int) position.y / 10);// working
			west = Game.getGrid((int)( position.x / 10) - 1, (int) position.y / 10);// not
																					// working
			south = Game.getGrid((int) position.x / 10, (int) position.y / 10 + 1);// working
			found = true;
		}
	}

The program is only working when getting the east and south tiles.

I just don’t understand why this could be happening.

I don’t think that catching the out of bounds exception is a good idea, because that stack trace will show you what to fix.


(int)(position.x / 10) - 1

This will be negative if position.x is less than 10. The cast to int has higher precedence than the subtraction.
You probably want icode(position.x / 10 - 1)[/icode] (Note that this is still -1 for x = 0)

Also, [icode]catch (ArrayIndexOutOfBoundsException e)[/icode] is monstrous.

Every value is well above 10

Also, How do I handle Out Bounds Exceptions then?

Let them be thrown and fix the code throwing them.

Is this better? :


public static Grid getGrid(float x, float y) {
		Grid r = null;
		if (x < channels.length && y < channels[0].length && x > 0 && y > 0) {
			r = channels[(int) x][(int) y];
		} else {
			r = new Grid();
		}
		return r;
	}


If that’s the behavior you want, then yes. (assuming a rectangular array)