繁体   English   中英

如何搜索2D字符串数组-Java

[英]How to search a 2D String array - Java

public class someClass{
public String[][] board = new String[7][7];

public someClass(){
    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i].length; j++) {
            board[i][j] = " ";
        }
    }
}

我在正在使用的类中遇到这个问题,我努力寻找一种搜索数组的方法,以查看特定单元格左,右,上方或下方的单元格是否为空或已填充。

IE board[4][2] -如何查看数组以查看位置[4] [1],[4] [3],[3] [2]和[5] [2]是否为空或里面有什么元素?

编辑:我试图使用嵌套的for循环来遍历数组,并从循环中的索引中减去1,但是什么也没提供。

public class someClass{

    public String[][] board = new String[7][7];

    public List<Coordinates> findAdjacentCells(final String[][] board, final int x, final int y){
        List<Coordinates> result = new ArrayList<Coordinates>();

        if(x >= 1 && y >= 1) {
            if(y + 1 < board[x].length)
                result.put(new Coordinates(x, y + 1));
            if(y - 1 >= 0)
                result.put(new Coordinates(x, y -1));
            if(x + 1 < board.length)
                result.put(new Coordinates(x+1, y));
            if(x -1 >= 0)
                result.put(new Coordinates(x-1, y));
        }

        return result;
    }
        // Keep track of coordinates
        public class Coordinates {
            int positionX;

            int positionY;

            public Coordinates(int positionX, int positionY) {
                super();
                this.positionX = positionX;
                this.positionY = positionY;
        }

        public final int getPositionX() {
            return positionX;
        }

        public final int getPositionY() {
            return positionY;
        }
    }
}

您可以执行上述操作。 我不知道您的电路板的位置是否为0。显然数组确实如此。 因此,您可能必须更改一些条件。

编辑:您编辑了问题并添加了更多代码,这可能不再相关。

Above: [i][j - 1]
Below: [i][j + 1]
Before: [i - 1][j]
After: [i + 1][j]

只需确保先检查界限即可。 然后:

private boolean isInBounds(int i, int j) {
    return (board.length > 0 && i >= 0 && i < board.length && j >= 0 && j < board[i].length);
}

private boolean isAboveEmpty(int i, int j) { // This might be a little verbose...
    int newJ = j - 1;
    if(isInBounds(i, newJ)) 
        return board[i][newJ].equals(" "); //Above cell is empty
    return true; // out of bounds cells are always empty (or are they?)
}

然后重复其他方向。 也将board设为私有,并让用户使用set方法设置单元格,因此您可以先进行检查。

public class Board {
    private String[][] board = new String[7][7];
    ...
    public void set(int i, int j, String value) {
        if(isInBounds(i, j) && isAboveEmpty(i, j) && isBelowEmpty(i, j) && isBeforeEmpty(i, j) && isAfterEmpty(i, j)) {
            board[i,j] = value;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM