java grid/board for 循环:哪一行是空的且最近?
java grid/board for-loop: what row is empty and nearest?
假设我有一个创建 4x8 板的程序。棋盘上的每个单元格要么是彩色对象,要么是空单元格对象。我如何找到我的板上哪一行是空的并且最接近第 0 行?
我的尝试:
public int emptyRow() {
int emptyCells = 0;
int emptyRow;
for (int i = 0; i < getMaxRows(); i++){
for (int j = 0; j < getMaxCols(); j++){
if (getBoardCell(i,j).equals(BoardCell.EMPTY)){
emptyCells++;
if (emptyCells == getMaxCols()){
return i;
}
}
}
}
但我意识到这将计算所有空单元格,而我只想在一行中有 8 个空单元格。
您首先需要为内部 for 循环创建一个变量来计算该特定行中的项目数,这样您就可以确定它是否为空。如果您从第 0 行开始,那么您找到的第一行将是最近的行。像这样。
int[][] myBoard = {{1,1,1},{0,0,0},{1,1,1}};
for(int i = 0; i < myBoard.length; i++) {
int count = 0;
//Loop through the columns of the row
for(int j = 0; j < myBoard[i].length; j++) {
//Check to see if the column for this row is empty if it is add
//to our empty cell count
if(myBoard[i][j] == 0) count ++;
}
//If our count is equal to the amount of columns in a row we return
//the row index.
if(count == myBoard[i].length()) return i;
}
假设我有一个创建 4x8 板的程序。棋盘上的每个单元格要么是彩色对象,要么是空单元格对象。我如何找到我的板上哪一行是空的并且最接近第 0 行?
我的尝试:
public int emptyRow() {
int emptyCells = 0;
int emptyRow;
for (int i = 0; i < getMaxRows(); i++){
for (int j = 0; j < getMaxCols(); j++){
if (getBoardCell(i,j).equals(BoardCell.EMPTY)){
emptyCells++;
if (emptyCells == getMaxCols()){
return i;
}
}
}
}
但我意识到这将计算所有空单元格,而我只想在一行中有 8 个空单元格。
您首先需要为内部 for 循环创建一个变量来计算该特定行中的项目数,这样您就可以确定它是否为空。如果您从第 0 行开始,那么您找到的第一行将是最近的行。像这样。
int[][] myBoard = {{1,1,1},{0,0,0},{1,1,1}};
for(int i = 0; i < myBoard.length; i++) {
int count = 0;
//Loop through the columns of the row
for(int j = 0; j < myBoard[i].length; j++) {
//Check to see if the column for this row is empty if it is add
//to our empty cell count
if(myBoard[i][j] == 0) count ++;
}
//If our count is equal to the amount of columns in a row we return
//the row index.
if(count == myBoard[i].length()) return i;
}