Java数组索引越界
好的,我的代码的一部分似乎出现了数组索引越界错误。具体在第 85-102 行...
我的代码: http://www.sosos.pastebin.com/ f0JQBWui
我只是想让它提前检查是否有被阻挡的图块,这样我的精灵就不会朝它不能移动的方向移动。仅当我位于地图的右角或下角时,才会发生此异常。
我猜为什么会发生这个错误,因为当我在拐角处时..它会检查其右侧和底部不存在的瓷砖...
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 which are not there...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
1)你实现blocked(tx,ty)的方式,它只接受合法的棋盘坐标(0<=tx<=12和0<=ty<=8)。否则,它会检查非法数组位置,并产生 ArrayIndexOutOfBoundsException。你确定这是你的意图吗?我认为将板外瓷砖视为阻塞是有道理的。
2)第85-102行似乎有很多错误。我认为你的意思是这样的:
无论如何,如果你按照我的建议修复(1),每个方向的额外约束条件是不必要的。
3) isInBound(r,c) 实现不正确。由于 c 上的条件,它总是返回 false。
4)代码还有很多其他问题,我就不细说了。原则上,尽量使设计简单并确保代码不会重复。
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:
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.
您必须在 blocked() 函数中进行一些边界检查。确保他们给你的坐标确实存在,如果不存在,则返回一些“阻止”值。
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.
在底部或右侧获取错误的描述似乎表明您需要测试该值是否超出数组边界。看看 Array.length
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