Java:检查数组是否有0和where;
Java: checkin whether array have 0 and where;
我正在 java 中构建一个 2048,我正在尝试检查数组中的哪些位置是空闲的(free = 其中有 0)以便将此空闲空间 col 和 row 传递到列表中.现在我有一个这样的网格,我需要以某种方式检查所有值并找到哪些地方是空闲的。
数组的样子:
Grid size is 4 x 4
1 2 3 4
================
1| 0 | 0 | 0 | 0 |
--+---+---+--
2| 0 | 0 | 0 | 0 |
--+---+---+--
3| 0 | 0 | 0 | 0 |
--+---+---+--
4| 0 | 0 | 0 | 0 |
================
这只是我现在要检查的内容
public static void addNewNum(int[][]grid) {
List freeSpace = new ArrayList();
for(int row=0; row< grid.length; row++) {
for(int col=0; col< grid[row].length; col++) {
if (grid[row][col] ==0) {
freeSpace.add(col);
freeSpace.add(row);
}
}
如果必须将值传递给列表,则需要定义适当的 class:
public final class Coordinate{
private final int row;
private final int col;
public Coordinate(final int row, final int col){
this.row = row;
this.col = col;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
}
}
然后将您的列表定义更改为:
List<Coordinate> freeSpace = new ArrayList<>();
然后添加一个免费的space坐标:
freeSpace.add(new Coordinate(row,col));
因此,您的 addNewNum 方法现在看起来如下:
public static void addNewNum(int[][]grid) {
List<Coordinate> freeSpace = new ArrayList<>();
for(int row=0; row< grid.length; row++) {
for(int col=0; col< grid[row].length; col++) {
if (grid[row][col] ==0) {
freeSpace.add(new Coordinate(row,col));
}
}
我正在 java 中构建一个 2048,我正在尝试检查数组中的哪些位置是空闲的(free = 其中有 0)以便将此空闲空间 col 和 row 传递到列表中.现在我有一个这样的网格,我需要以某种方式检查所有值并找到哪些地方是空闲的。
数组的样子:
Grid size is 4 x 4
1 2 3 4
================
1| 0 | 0 | 0 | 0 |
--+---+---+--
2| 0 | 0 | 0 | 0 |
--+---+---+--
3| 0 | 0 | 0 | 0 |
--+---+---+--
4| 0 | 0 | 0 | 0 |
================
这只是我现在要检查的内容
public static void addNewNum(int[][]grid) {
List freeSpace = new ArrayList();
for(int row=0; row< grid.length; row++) {
for(int col=0; col< grid[row].length; col++) {
if (grid[row][col] ==0) {
freeSpace.add(col);
freeSpace.add(row);
}
}
如果必须将值传递给列表,则需要定义适当的 class:
public final class Coordinate{
private final int row;
private final int col;
public Coordinate(final int row, final int col){
this.row = row;
this.col = col;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
}
}
然后将您的列表定义更改为:
List<Coordinate> freeSpace = new ArrayList<>();
然后添加一个免费的space坐标:
freeSpace.add(new Coordinate(row,col));
因此,您的 addNewNum 方法现在看起来如下:
public static void addNewNum(int[][]grid) {
List<Coordinate> freeSpace = new ArrayList<>();
for(int row=0; row< grid.length; row++) {
for(int col=0; col< grid[row].length; col++) {
if (grid[row][col] ==0) {
freeSpace.add(new Coordinate(row,col));
}
}