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

Java中如何向二维int数组指定列的首个空白位置插入整数

解决二维棋盘指定列第一个空白位置填充1的问题

核心问题分析

你的代码当前存在两个关键问题:

  • 列索引对应错误:Java数组索引从0开始,但你将"A"对应索引1、"B"对应索引2,导致修改了错误的列。
  • 循环逻辑错误:遍历整列所有行并赋值为1,而非定位到目标列中第一个需要填充的空白位置(即现有非0元素下方的第一个0)。

正确实现思路

  1. 将输入的列字母(A-F)映射为对应的数组索引:A→0,B→1,C→2,D→3,E→4,F→5。
  2. 遍历目标列,找到该列中最后一个非0元素的行号。
  3. 在最后一个非0元素的下一行(如果该行存在于棋盘范围内),将该位置设置为1。

修正后的完整代码

public class putNumberSO {
    public static int[][] board = {
            {1, 2, 3, 2, 2, 3},
            {3, 2, 2, 1, 1, 2},
            {3, 1, 1, 1, 2, 2},
            {2, 2, 1, 3, 2, 2},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0}
    };

    public static void main(String[] args) {
        printGrid(putNumber(board, "B"));
    }

    public static int[][] putNumber(int[][] board, String columnInput) {
        // 将列字母转换为数组索引
        int colIndex;
        switch (columnInput) {
            case "A":
                colIndex = 0;
                break;
            case "B":
                colIndex = 1;
                break;
            case "C":
                colIndex = 2;
                break;
            case "D":
                colIndex = 3;
                break;
            case "E":
                colIndex = 4;
                break;
            case "F":
                colIndex = 5;
                break;
            default:
                throw new IllegalArgumentException("输入的列无效,请输入A-F之间的字母");
        }

        // 找到目标列中最后一个非0元素的行号
        int lastNonZeroRow = -1;
        for (int row = 0; row < board.length; row++) {
            if (board[row][colIndex] != 0) {
                lastNonZeroRow = row;
            }
        }

        // 在最后一个非0元素的下一行填充1(确保该行存在)
        int targetRow = lastNonZeroRow + 1;
        if (targetRow < board.length) {
            board[targetRow][colIndex] = 1;
        }

        return board;
    }

    public static void printGrid(int[][] grid) {
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                // 添加空格分隔元素,输出更清晰
                System.out.print(grid[i][j] + " ");
            }
            System.out.println();
        }
    }
}

效果验证

当输入列"B"时,代码会准确定位到列B中最后一个非0元素(第4行,索引3)的下一行(第5行,索引4),将该位置的0替换为1,输出结果与你的需求完全一致:

1 2 3 2 2 3 
3 2 2 1 1 2 
3 1 1 1 2 2 
2 2 1 3 2 2 
0 1 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:15:29