簡體   English   中英

將一個二維數組的坐標復制到另一個數組

[英]Copy coordinates of one 2D array to another array

我有一個代表xy坐標的二維數組freeSpace[][] 如果空間是“不空閑的”,那么我將它標記為77 ,其他1

我想將所有標記為77的元素放入它自己的數組中,並帶有這些特定的數組坐標。 我認為它應該很簡單,但我就是無法正確使用語法。

這是我的代碼:

for (int v = 0; v < info.getScene().getHeight(); v++) {
    for (int h = 0; h < info.getScene().getWidth(); h++) {
        //System.out.print(freeSpace[h][v] != 77 ? "." : "#");
        if (freeSpace[h][v] == 77) {
            blockedCoordinates = new int[][]{{h, v}};
        }
    }
    System.out.println();
}

我已經聲明了blockedCoordinates[][]數組。

我的大多數嘗試都導致了一個空數組。

您在復制數據時遇到了一些錯誤,原因如下:

// assuming following definition
int[][] blockedCoordinate = new int[][]{};

for (int v = 0; v < info.getScene().getHeight(); v++) {
    for (int h = 0; h < info.getScene().getWidth(); h++) {
        //System.out.print(freeSpace[h][v] != 77 ? "." : "#");
        if (freeSpace[h][v] == 77) {
            // Make a copy
            int[][] copyBlockedCoordinate = blockedCoordinates;
            // extend the array length by 1
            blockedCoordinates = new int[copyBlockedCoordinate.length + 1][2];
            for (int i = 0; i < copyBlockedCoordinate.length; i++) {
                for (int j = 0; j < copyBlockedCoordinate[i].length; j++) {
                    blockedCoordiante[i][j] = copyBlockedCoordinate[i][j];
                }
            }
            // add new array at new or last index position in blockedCoordinate array
            blockedCoordinate[copyBlockedCoordinate.length] = {h, v};
        }
    }
    // Moake sure you write what you want to the console here to debug :)
    System.out.println();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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