簡體   English   中英

如何搜索二維數組中的任何索引?

[英]How do you search around any index in a 2D array?

所以我正在制作一個程序,它接收一個 5x5 的二​​維數組,並列出數組的任何給定索引周圍的所有字符。 例如,如果我輸入 list[1][1],它將給出索引:[0][0], [0][1], [0][2], [1][0], [1] ][2]、[2][0]、[2][1]、[2][2]。

我可以打印出索引周圍的所有字母,但邊緣的字母除外,例如索引 [0][0]。 我似乎無法弄清楚如何克服這一點。

 private static void checkSurrounding(char[][] list, int x, int y) {
    for(int dx = -1; dx <= 1; dx++) {
        for(int dy = -1; dy <= 1; dy++) {
            if(!(dx == 0 && dy == 0)) {
                System.out.print(list[x + dx][y + dy]);
            }
        }
    } 
}

你的代碼幾乎是正確的! 您在這里排除中間點:

 private static void checkSurrounding(char[][] list, int x, int y) {
    for(int dx = -1; dx <= 1; dx++) {
        for(int dy = -1; dy <= 1; dy++) {
            if(!(dx == 0 && dy == 0)) {
                System.out.print(list[x + dx][y + dy]);
            }
        }
    } 
}

你唯一想念的是避免越界。 只要確保你沒有越界,它應該可以完美地工作:

 private static void checkSurrounding(char[][] list, int x, int y) {
    for(int dx = -1; dx <= 1; dx++) {
        if ((x + dx >= 0) && (x + dx < list.length)) {
            for(int dy = -1; dy <= 1; dy++) {
                if ((y + dy >= 0) && (y + yd < list[x + dx].length) && (!(dx == 0 && dy == 0))) {
                    System.out.print(list[x + dx][y + dy]);
                }
            }
        }
    } 
}

暫無
暫無

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

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