gpt4 book ai didi

java - 在java中加载二维数组的所有值

转载 作者:搜寻专家 更新时间:2023-10-31 20:16:54 25 4
gpt4 key购买 nike

我正在尝试创建一个 2d 拼图 slider 游戏。我创建了自己的名为 gamestate 的对象来存储父游戏状态和新游戏状态,因为我计划使用 BFS 解决它。示例数组看起来像

int[][] tArr = {{1,5,2},{3,4,0},{6,8,7}};

这意味着

[1, 5, 2,3, 4, 0,6, 8, 7]

为了存储此状态,我使用了以下 for 循环,它带来了 indexOutOfBounds 异常

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]; 更改为 this.state = new int[state.length][state.length > 0 ?状态[0].length : 0];

这样,你初始化数组的容量为

(state.length)x(state[0].length0 如果 state.length0) 个元素。

另外,你必须 for 循环直到 state.length with i 和直到 state[i].length with 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]]

关于java - 在java中加载二维数组的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52608711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com