首页 > 解决方案 > 向后捕获 ArrayIndexOutOfBoundsException?

问题描述

我创建吃豆人游戏。我有大小为 15x15 的数组,共有 225 个字段。当我从 255 移动到 ie256 时,我得到了 ArrayIndexOutOfBoundsException,这是有道理的。所以我可以抓住它并做一些操作,假设我设置了 pacman 的新起点。但是,如果我从第 75 场转到第 74 场,则什么也没有发生。所以我问,我能不能抓住这个并做一些操作,就像我上面提到的那样。

标签: java

解决方案


你不应该依赖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];
}

推荐阅读