我正在创建一个可在android应用中使用的类。它应跟踪可能改变颜色的“平铺”网格。但是当我创建的“ checkTile”方法被调用时,它总是崩溃。该方法仅通过一些if语句运行,以查看周围的图块是否为“空白”,然后在任何空白图块上调用“ switchTile”命令,从而交换两个imageview的可绘制对象。
logcat说:3474-3474 /? E / VCD:init_modem:无法打开/ dev / umts_atc0,errno = 2
这里是课程:
import android.graphics.drawable.Drawable;
import java.util.ArrayList;
import java.util.Random;
public class TileBoard {
private Drawable[][] tiles;
private Drawable blank;
public TileBoard(int width, int height, Drawable blank) {
tiles = new Drawable[width][height];
this.blank = blank;
}
public void switchTiles(int tile1X, int tile1Y, int tile2X, int tile2Y) {
Drawable placeholder = tiles[tile1X][tile1Y];
tiles[tile1X][tile1Y] = tiles[tile2X][tile2Y];
tiles[tile2X][tile2Y] = placeholder;
}
public void checkTile(int tileX, int tileY) {
if (tileX != 0) if (tiles[tileX - 1][tileY].equals(blank))
switchTiles(tileX, tileY, tileX - 1, tileY);
if (tileY != 0) if (tiles[tileX][tileY - 1].equals(blank))
switchTiles(tileX, tileY, tileX, tileY - 1);
if (tileX != tiles[0].length) if (tiles[tileX + 1][tileY].equals(blank))
switchTiles(tileX, tileY, tileX + 1, tileY);
if (tileY != tiles.length) if (tiles[tileX][tileY + 1].equals(blank))
switchTiles(tileX, tileY, tileX, tileY + 1);
}
public void scrambleBoard() {
Random rand = new Random();
for (int i = 0; i < tiles[0].length; i++) {
for (int j = 0; j < tiles.length; j++) {
int randomPositionX = rand.nextInt(tiles[0].length);
int randomPositionY = rand.nextInt(tiles.length);
switchTiles(i, j, randomPositionX, randomPositionY);
}
}
}
public void setBoard(ArrayList<Drawable> images) {
for (int i = 0; i < tiles.length * 5; i += 5) {
for (int j = 0; j < tiles[0].length; j++) {
tiles[j][i / 5] = images.get(i + j);
}
}
}
}
问题已解决。有两件事是错误的。首先,在某些checkTile中的if语句中,需要使用条件tileY != tiles.length - 1
而不是tileY != tiles.length
。 -1的缺失导致ArrayIndexOutOfBoundsException
。其次,我试图将可绘制对象与.equals
命令进行比较,该命令显然不适用于可绘制对象。