You need to enable JavaScript to run this app. Java如何读取首行为棋盘尺寸的空白分隔文本并生成2D Array?
优惠活动
大模型
产品
解决方案
定价
更多

Java如何读取首行为棋盘尺寸的空白分隔文本并生成2D Array?

Java读取指定格式棋盘文件并解析为二维数组的实现

目标文件格式约定:第一行存储棋盘边长n,后续共n行、每行n个整数,所有数值间以任意空白符(空格、换行、制表符等)分隔。

实现核心逻辑

  • 读取首行的整数n,初始化n×n的二维数组
  • 按行优先顺序读取剩余的n²个整数,依次填充到二维数组中
  • 增加格式校验,避免文件内容不符合约定时出现运行时错误

简洁实现(基于Scanner)

适合快速开发,无需手动处理空白符分割,自动兼容任意格式的空白分隔:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class BoardLoader {
    public static int[][] load(String filePath) throws IOException {
        // try-with-resources自动关闭IO流,避免资源泄漏
        try (Scanner sc = new Scanner(new File(filePath))) {
            // 读取首行得到棋盘尺寸
            int size = sc.nextInt();
            int[][] board = new int[size][size];

            // 逐行逐列填充数组
            for (int row = 0; row < size; row++) {
                for (int col = 0; col < size; col++) {
                    if (!sc.hasNextInt()) {
                        throw new IOException("文件内容不足,缺少" + size + "×" + size + "个数值");
                    }
                    board[row][col] = sc.nextInt();
                }
            }

            // 校验是否存在多余内容
            if (sc.hasNextInt()) {
                throw new IOException("文件存在未识别的多余数值");
            }
            return board;
        }
    }

    public static void main(String[] args) {
        // 替换为实际文件路径即可运行
        String filePath = "你的棋盘文件路径";
        try {
            int[][] board = load(filePath);
            // 打印验证解析结果
            for (int[] row : board) {
                for (int num : row) {
                    System.out.printf("%d\t", num);
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

实现说明

  • Scanner.nextInt()会自动跳过所有类型的空白符,不管数值是用空格、制表符还是换行分隔,都能正确按顺序读取,完全匹配题目中的文件格式要求
  • 内置了基础格式校验,当文件数值数量不对时会抛出明确的异常,避免静默错误或数组索引越界
  • 使用try-with-resources语法,无需手动关闭流,降低资源泄漏风险

逐行校验实现(基于BufferedReader)

如果需要严格匹配“逐行排布数值”的格式,校验每行的数值个数是否符合要求,可以使用该版本:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BoardLoaderStrict {
    public static int[][] load(String filePath) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            // 读取首行尺寸
            int size = Integer.parseInt(br.readLine().trim());
            int[][] board = new int[size][size];

            // 逐行读取处理
            for (int row = 0; row < size; row++) {
                String line = br.readLine();
                // 自动跳过空行,提升容错性
                while (line != null && line.trim().isEmpty()) {
                    line = br.readLine();
                }
                if (line == null) {
                    throw new IOException("行数不足,缺少第" + (row + 1) + "行数值");
                }
                // 按任意空白符分割行内数值
                String[] nums = line.trim().split("\\s+");
                if (nums.length != size) {
                    throw new IOException("第" + (row + 1) + "行数值个数为" + nums.length + ",不符合" + size + "个的要求");
                }
                // 转换为int填入数组
                for (int col = 0; col < size; col++) {
                    board[row][col] = Integer.parseInt(nums[col]);
                }
            }
            return board;
        }
    }
}

实现说明

  • 严格按行读取校验,能精准识别某一行数值个数不对的问题,和题目中“逐行排布p值”的格式匹配度更高
  • 自动跳过文件中的空行,对非故意的格式小问题有一定容错能力

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 05:45:03