[英]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.