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

二维数组查找首个空座位问题求助:代码仅输出最后一个空座位

二维数组查找首个空座位问题解决

问题场景

我和朋友尝试在boolean类型二维数组aud中查找首个空座位(false代表空座位),需要输出该座位的索引,但当前代码仅能输出最后一个空座位。

原代码:

public static void main(String[] args) {
    boolean[][] aud = { { true, true, true, true }, // rad 0
            { false, false, true, false }, // rad 1
            { true, false, true, true }, // rad 2
            { true, true, true, true }, // rad 3
    };
}

public static void firstEmptySeat(boolean[][] array) {
    String a = "";
    
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            if (array[i][j] == false) {
                a = i + "," + j;
            }
        }
    }
    System.out.println(a);
}

问题根源

代码会遍历所有座位,每找到一个空座位就覆盖变量a的值,遍历结束后自然保留的是最后一个空座位的索引,而非第一个。

解决方案

找到首个空座位后立即停止遍历,避免后续空座位覆盖结果。

方案1:找到即输出并终止方法

这是最简洁的实现,找到目标后直接打印结果并返回,无需继续遍历:

public static void firstEmptySeat(boolean[][] array) {
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            if (!array[i][j]) { // 等价于array[i][j] == false,写法更简洁
                System.out.println(i + "," + j);
                return; // 终止方法,不再继续遍历
            }
        }
    }
    // 处理无空座位的情况
    System.out.println("没有空座位");
}

方案2:用标记跳出双层循环

如果需要在找到座位后执行其他逻辑,可以用标记变量控制循环:

public static void firstEmptySeat(boolean[][] array) {
    boolean found = false;
    String seatIndex = "";
    
    for (int i = 0; i < array.length && !found; i++) {
        for (int j = 0; j < array[i].length; j++) {
            if (!array[i][j]) {
                seatIndex = i + "," + j;
                found = true;
                break; // 跳出内层循环
            }
        }
    }
    
    if (found) {
        System.out.println(seatIndex);
    } else {
        System.out.println("没有空座位");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:30:57