簡體   English   中英

在java中加載2d數組的所有值

[英]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].length0如果state.length0 )元素。

此外,你必須循環到state.lengthi ,直到state[i].lengthj

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM