【发布时间】:2019-03-07 14:27:14
【问题描述】:
我正在尝试创建一个 2d 益智滑块游戏。我创建了自己的名为 gamestate 的对象来存储父游戏状态和新的游戏状态,因为我计划使用 BFS 解决它。示例数组看起来像
int[][] tArr = {{1,5,2},{3,4,0},{6,8,7}};
这意味着
[1, 5, 2, 3, 4, 0, 6、8、7]
为了存储这个状态,我使用了下面的 for 循环,它带来了 indexOutOfBounds exceptions。
public class GameState {
public int[][] state; //state of the puzzle
public GameState parent; //parent in the game tree
public GameState() {
//initialize state to zeros, parent to null
state = new int[0][0];
parent = null;
}
public GameState(int[][] state) {
//initialize this.state to state, parent to null
this.state = state;
parent = null;
}
public GameState(int[][] state, GameState parent) {
//initialize this.state to state, this.parent to parent
this.state = new int[0][0];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
this.state[i][j] = state[i][j];
}
}
this.parent = parent;
}
关于如何解决这个问题的任何想法?
【问题讨论】:
-
在第三个构造函数中,您使用
new int[0][0]初始化state。然后您无法访问数组的任何元素。 -
附带说明,它不是
[1, 5, 2, 3, 4, 0, 6, 8, 7],而是[[1, 5, 2], [3, 4, 0], [6, 8, 7]]。见我的answer
标签: java arrays 2d indexoutofboundsexception