[英]Loading all values of 2d array in java
我正在尝试创建一个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;
}
有想法该怎么解决这个吗?
GameState()
构造函数(默认构造函数): 改变这个state = new int[0][0];
对此: state = new int[
3
][
3
];
。 这样就可以初始化具有(3)x(3)元素容量的数组。
GameState(int[][] state, GameState parent)
构造函数: 改变这个this.state = new int[0][0];
to this.state = new int[
state.length
] [ state.length > 0 ? state[0].length : 0
state.length > 0 ? state[0].length : 0
];
这样,您可以初始化具有容量的阵列
( state.length
)x( state[0].length
或0
如果state.length
为0
)元素。
此外,你必须循环到state.length
与i
,直到state[i].length
与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;
}
另外,作为附注,它不是[1, 5, 2, 3, 4, 0, 6, 8, 7]
,
但是[[1, 5, 2], [3, 4, 0], [6, 8, 7]]
。
问题出在初始化部分。
this.state = new int[0][0];
此代码将创建零大小的二维aray。 这就是当您尝试在其中设置值时获得indexOutOfBounds异常的原因。
如果要使用零初始化数组,则正确的语法是:
this.state = {{0,0,0},{0,0,0},{0,0,0}};
请参阅官方文档以获取完整参考: https : //docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
在第3个构造函数中,您使用空数组初始化this.state
。 它没有元素,因此长度为0
。 使用for循环访问此数组的任何元素会引发ArrayIndexOutOfBoundsException
。
由于您将state
作为参数传递,因此您可能希望将其值复制到字段state
。
你可以这样做:
public GameState(int[][] state, GameState parent) {
this.state = new int[state.length][];
for (int i = 0; i < state.length; i++) {
if (state[i] != null) {
this.state[i] = Arrays.copyOf(state[i], state[i].length);
}
}
this.parent = parent;
}
你当然可以调用Arrays.of(state)
但这不会返回一个深层的state
副本。 对于每一个i
,你将不得不this.state[i] == state[i]
进一步阅读: 如何在Java中复制2维数组?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.