java - 向后捕获 ArrayIndexOutOfBoundsException?
问题描述
我创建吃豆人游戏。我有大小为 15x15 的数组,共有 225 个字段。当我从 255 移动到 ie256 时,我得到了 ArrayIndexOutOfBoundsException,这是有道理的。所以我可以抓住它并做一些操作,假设我设置了 pacman 的新起点。但是,如果我从第 75 场转到第 74 场,则什么也没有发生。所以我问,我能不能抓住这个并做一些操作,就像我上面提到的那样。
解决方案
你不应该依赖ArrayIndexOutOfBoundsException
正常的逻辑。此异常表示编程错误。
相反,您应该在增加它之前检查索引:
if (currentIndex == 255) {
// "special logic"
} else {
// "usual logic"
}
这样您还可以处理任何“特殊”索引,例如
if ((currentIndex + 1) % 15 == 0) {
// "special logic"
} else {
// "usual logic"
}
另一点:如果您正在编写 2-D 游戏,请考虑使用两个索引 - x 和 y。每一步都会修改 x 和/或 y,这可以像 pacman 中一样轻松“环绕”(例如 13 -> 14 -> 15 -> 1 -> 2 -> ...)。并且仅当您需要访问字段元素时才将 (x,y)-Pair 转换为索引:
// Assuming that x and y are 1-based, not 0-based:
public FieldElement getFieldElementAtPosition(final int x, final int y) {
final int index = (y - 1) * FIELD_WIDTH + x - 1;
return fieldArray[index];
}
推荐阅读
- angularjs - 如何使用我从 Ionic 中的 REST api 检索到的结果
- ios - 我可以使用 Callkit SDK 设置对 SIP URI 的呼叫吗
- http - HEAD 请求返回响应的后果
- ios - 适用于 iOS 的全屏背景图像分辨率
- javascript - 将 Drop Ship PO 添加到 NetSuite 中的现有销售订单
- tensorflow - 当前一层中的 mask_zero=True 时,由于连接层,Keras 图像字幕模型无法编译
- react-native - 如何自定义 headerLeft React Navigation?
- ssas - SSAS 表格表达式表无法从 SQL Server 数据源加载
- java - Java Optional 与传统的缺失值处理有何不同?或者如何正确使用Java Optional
- assembly - (缓冲区溢出利用)无法覆盖 $ebp 和 $eip 寄存器