开发者

Java Array Index out of Bounds

OK so I seem to be getting an Array Index out of Bounds error in a part of my code. Specifically in lines 85-102...

My code: http://www.sosos.pastebin.com/f0JQBWui

I just want it to check for blocked tiles AHEAD of time that way my sprite doesn't move in the direction it can't. This exception only happens when I am on the RIGHT or BOTTOM corners of my map.

My GUESS of why this error happens if because when I am on the corner.. it checks for the tiles to the RIGHT and BOTTOM of it whic开发者_C百科h are not there...


1) The way you implemented blocked(tx,ty), it only accepts legal board coordinates (0<=tx<=12 and 0<=ty<=8). Otherwise it checks an illegal array position, producing an ArrayIndexOutOfBoundsException. Are you sure this is your intention? I think it makes sense to consider off board tiles as blocked.

2) In lines 85-102 there seems to be many errors. I think you meant something like:

        if (spawnX == 0 || blocked(spawnX - 1, spawnY)) {
            left = false;
            System.out.println("You can't go left!");
        }           
        if (spawnX == 12 || blocked(spawnX + 1, spawnY)) {
            right = false;
            System.out.println("You can't go right!");
        }
        if (spawnY ==0 || blocked(spawnX, spawnY - 1)) {
            up = false;
            System.out.println("You can't go up!");
        }
        if (spawnY == 8 || blocked(spawnX, spawnY + 1)) {
            down = false;
            System.out.println("You can't go down!");
        }

Anyway, if you fix (1) as I suggested, the extra bound condition per direction is unecessary.

3) isInBound(r,c) is implemented incorrectly. It always returns false, due to the conditions on c.

4) There are many other problems with the code, but I will not enter into details. As a principle, try to make your design simple and make sure the code does not repeat itself.


You're going to have to do some bounds-checking in your blocked() function. Make sure that the coordinates they're giving you actually exist and return some "blocked" value if they don't.


The description of getting the error at the bottom or right would seem to suggest that you need to test if the value exceeds the array bounds. Have a look at Array.length

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜