You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生成电脑舰船位置函数遇问题:Android Studio冻结崩溃

解决Android Studio因随机舰船位置导致的冻结崩溃问题

老哥,我赌你十有八九是踩了无限循环的坑!这种随机生成坐标却没处理“无空位可用”的情况,很容易让程序卡死甚至崩溃——尤其是当棋盘快被占满的时候,随机数一直撞已占用的位置,就会陷入死循环,触发Android的ANR(应用无响应),最后直接崩掉。

问题根源分析

你原来的代码大概率是类似这样的逻辑:

Random random = new Random();
// 无限循环碰运气找空位
while (true) {
    int x = random.nextInt(5);
    int y = random.nextInt(5);
    if (board[x][y] == 0) {
        board[x][y] = 2;
        break;
    }
    // 一旦棋盘没有空位,这里会永远循环下去!
}

当棋盘上没有空位(全是1或2)时,这个循环根本停不下来,直接把CPU占满,导致Studio冻结崩溃。

靠谱的解决方案

推荐两种高效且安全的写法,彻底避免无限循环:

方案1:先收集所有空位,再随机选取

先遍历棋盘把所有0(空位)的坐标存起来,再从这个列表里随机挑位置,既不会重复也不会卡循环:

// 第一步:收集所有空位坐标
List<int[]> emptySpots = new ArrayList<>();
for (int row = 0; row < 5; row++) {
    for (int col = 0; col < 5; col++) {
        if (board[row][col] == 0) {
            emptySpots.add(new int[]{row, col});
        }
    }
}

// 第二步:如果还有空位,随机选一个放电脑舰船
if (!emptySpots.isEmpty()) {
    Random random = new Random();
    int[] chosenSpot = emptySpots.get(random.nextInt(emptySpots.size()));
    board[chosenSpot[0]][chosenSpot[1]] = 2;
} else {
    // 可以加个日志提示棋盘已满,无法放置
    Log.d("ShipPlacement", "棋盘已满,无法放置电脑舰船");
}

方案2:给循环加退出条件(适合简单场景)

如果不想收集列表,也可以给循环加最大尝试次数,防止无限循环:

Random random = new Random();
int maxAttempts = 100; // 足够覆盖5x5棋盘的尝试次数
int attempts = 0;
boolean placed = false;

while (attempts < maxAttempts) {
    int x = random.nextInt(5);
    int y = random.nextInt(5);
    if (board[x][y] == 0) {
        board[x][y] = 2;
        placed = true;
        break;
    }
    attempts++;
}

if (!placed) {
    Log.d("ShipPlacement", "尝试多次仍无法找到空位,棋盘可能已满");
}

额外提示

如果要放置多艘电脑舰船,方案1会更高效——每次选完位置后,从emptySpots列表里移除该坐标,下次直接从剩余空位里选就行,完全不用担心重叠问题。

内容的提问来源于stack exchange,提问作者Bagsimcwt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:40:04