Mat*_*rew 5 java arrays 2d indexoutofboundsexception
我正在尝试创建一个2D拼图滑块游戏.我创建了自己的对象gamestate来存储父游戏状态和新的游戏状态,因为我计划使用BFS解决它.示例数组看起来像
int[][] tArr = {{1,5,2},{3,4,0},{6,8,7}};
Run Code Online (Sandbox Code Playgroud)
这暗示着
[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;
}
Run Code Online (Sandbox Code Playgroud)
有想法该怎么解决这个吗?
GameState()构造函数(默认构造函数):将其更改state = new int[0][0];为:。这样,您就可以用 (3)x(3) 个元素的容量来初始化数组。state = new int[3][3];
GameState(int[][] state, GameState parent)构造函数:将其更改this.state = new int[0][0];为this.state = new int[state.length][state.length > 0 ? state[0].length : 0];
这样,您就可以用容量初始化数组
( state.length)x(state[0].length或0if state.lengthis 0) 元素。
另外,您必须 for 循环,直到state.lengthwithi和直到state[i].lengthwith j。
在GameState构造函数中,像这样:
public GameState(int[][] state, GameState parent) {
//initialize this.state to state, this.parent to parent
this.state = new int[state.length][state.length > 0 ? state[0].length : 0];
for (int i = 0; i < state.length; i++){
for (int j = 0; j < state[i].length; j++) {
this.state[i][j] = state[i][j];
}
}
this.parent = parent;
}
Run Code Online (Sandbox Code Playgroud)
另外,作为旁注,它不是[1, 5, 2, 3, 4, 0, 6, 8, 7],
但[[1, 5, 2], [3, 4, 0], [6, 8, 7]]。
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |