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

Java如何读取txt文件数据并转换为二维数组(附报错代码)

报错核心原因

你遇到的编译报错根源是变量名冲突:开头定义了File file = new File("map1.txt");,这个file是java.io.File类型的对象,后续你却试图给它赋值char二维数组file = new char[strings.size()][strings.size()];,再用file[i][j]做数组访问时,编译器自然会提示「类型不匹配,File类型不能作为数组使用」。

除了这个直接触发报错的问题,你现有代码还有多处逻辑错误,就算改了变量名也跑不起来:

  • 完全缺失文件读取逻辑:定义了Scanner参数但从未调用它读取文件内容,反而写了strings.add(size)这种传int给要求String参数的add方法的错误代码,本身就无法编译
  • 遍历逻辑写错:遍历行内容时写的是for(char ch : strings.toCharArray()),strings是List<String>类型,根本没有toCharArray()方法
  • 合法字符判断逻辑错误:if(ch == allowed)是拿单个char和char数组做比较,永远不会判定为合法
  • 数组填充时索引未更新:遍历每行填充二维数组时,行索引i没有自增,列索引j处理完一行后没有重置为0,必然触发索引越界
  • 计数逻辑错误:chCounter在循环里重复自增两次,长度校验永远无法通过
  • 坐标计数错误:xCounter从未自增,值为2的玩家出生点坐标会完全算错
  • 硬编码size=8,没有读取文件第一行的尺寸值,换个地图文件就会出错

修正后的可运行实现
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 你代码中已有的自定义异常类
class InvalidMapException extends Exception {
    public InvalidMapException(String msg) {
        super(msg);
    }
}

// 你代码中已有的坐标类
class Position {
    public int x;
    public int y;
    public Position(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class GameMap {
    private final char[] allowed = {'0', '1', '2'};
    public List<Position> pPos = new ArrayList<>();
    // 存储地图的二维数组改名,避免和File对象重名
    public char[][] mapData;

    public GameMap(String mapPath) throws FileNotFoundException, InvalidMapException {
        // 自动管理Scanner资源,避免文件句柄泄漏
        try (Scanner scan = new Scanner(new File(mapPath))) {
            List<String> lineList = new ArrayList<>();
            // 读取第一行的地图尺寸
            if (!scan.hasNextInt()) {
                throw new InvalidMapException("地图第一行必须是正方形边长整数");
            }
            int size = scan.nextInt();
            // 读取整数后消费掉换行符,避免后续读行拿到空串
            scan.nextLine();

            // 逐行读取地图内容
            for (int i = 0; i < size; i++) {
                if (!scan.hasNextLine()) {
                    throw new InvalidMapException("地图行数不足,要求" + size + "行");
                }
                lineList.add(scan.nextLine().trim());
            }

            // 校验内容合法性 + 收集玩家出生点
            for (int y = 0; y < size; y++) {
                String[] cells = lineList.get(y).split(" ");
                if (cells.length != size) {
                    throw new InvalidMapException("第" + (y+1) + "行列数不匹配,要求" + size + "列");
                }
                for (int x = 0; x < size; x++) {
                    char cellVal = cells[x].charAt(0);
                    // 校验字符是否合法
                    boolean valid = false;
                    for (char c : allowed) {
                        if (cellVal == c) {
                            valid = true;
                            break;
                        }
                    }
                    if (!valid) {
                        throw new InvalidMapException("坐标(" + x + "," + y + ")存在非法字符:" + cellVal);
                    }
                    // 记录玩家出生点
                    if (cellVal == '2') {
                        pPos.add(new Position(x, y));
                    }
                }
            }

            // 填充二维数组
            mapData = new char[size][size];
            for (int y = 0; y < size; y++) {
                String[] cells = lineList.get(y).split(" ");
                for (int x = 0; x < size; x++) {
                    mapData[y][x] = cells[x].charAt(0);
                }
            }
        }
    }

    // 测试入口
    public static void main(String[] args) {
        try {
            GameMap map = new GameMap("map1.txt");
            System.out.println("地图读取成功,尺寸:" + map.mapData.length + "*" + map.mapData[0].length);
            System.out.println("玩家出生点数量:" + map.pPos.size());
            // 打印地图验证
            for (char[] row : map.mapData) {
                for (char c : row) {
                    System.out.print(c + " ");
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

关键改动说明
  • 把存储地图的二维数组改名为mapData,彻底解决和File对象的命名冲突,直接消除你遇到的编译报错
  • 补全完整的文件读取逻辑:先读第一行的尺寸值,再逐行读取地图内容,不需要硬编码尺寸,可适配任意大小的正方形地图
  • 改用split(" ")按空格分割每行的格子值,替代原来逐字符遍历跳空格的逻辑,从根源上避免计数错误
  • 修正所有遍历、判断、索引更新的逻辑错误,坐标计数、字符校验、长度校验都可以正常工作
  • 所有异常提示都带上具体错误位置,排查问题更方便

测试时把map1.txt放在项目根目录(和src文件夹同级)即可,如果文件放其他位置,替换成文件的绝对路径就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 03:36:25