java applet - 数组检查
好的,我的代码在这里: http://www.so.pastebin.com/m7V8rQ2n
我想知道什么...假设我有一个可以在图块上重绘的图像...有没有办法检查未来的图块,这样我就不会超出已定义的图块地图的范围?
就像如果我在地图的边缘......它不会让我过去?
谢谢。
OK so my code is here: http://www.so.pastebin.com/m7V8rQ2n
What I want to know... let's say I have an image which I can redraw on tiles... is there a way to check for future tiles so I DON'T go out of bounds of my already defined tile map?
Like if I were at the edge of a map... it would NOT let me go past it?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,只需确保索引在界限内即可防止 ArrayIndexOutOfBoundsException。
因此,像这样的简单检查是非常典型的:
除非像
arr
在检查和访问之间重新分配这样令人讨厌的事情,上面的代码将永远抛出ArrayIndexOutOfBoundsException< /代码>。
二维数组“板”
通常,您可以更加具体,例如,当您将矩形“板”存储在二维数组(或者更确切地说,Java 中的数组的数组)中时。
然后您可以使用如下方法:
绑定检查更易于阅读和编写,因为我们知道我们有一个 MxN 板。如果
isInBound(r, c)
,则board[r][c]
将永远抛出ArrayIndexOutOfBoundsException
。Generally speaking, preventing
ArrayIndexOutOfBoundsException
can be done by simply making sure that the index is within the bound.Thus, a simple check like this is quite typical:
Barring nasty things like
arr
getting reassigned between the check and the access, the above code will NEVER throwArrayIndexOutOfBoundsException
.2D array "boards"
Often, you can be a lot more specific, e.g. when you have rectangular "boards" stored in a two-dimensional array (or rather, array of arrays in Java).
Then you can have a method like the following:
The bound check is both easier to read and to write, since we know that we have an MxN board. If
isInBound(r, c)
, thenboard[r][c]
will NEVER throwArrayIndexOutOfBoundsException
.