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

战舰游戏文本文件读取与数据存储功能实现求助

我来帮你补全这段代码,实现读取棋盘尺寸和舰船坐标的完整功能。咱们一步步拆解需求,完善代码:

完整实现代码
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class BattleshipFileReader {
    // 存储读取到的棋盘尺寸
    private int size;
    // 用映射存储舰船名称与对应坐标数组的关联
    private Map<String, int[][]> shipCoordinates = new HashMap<>();

    public void ReadFile(File f) throws FileNotFoundException {
        Scanner scanner = new Scanner(f);
        int lineNumber = 1;

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            // 跳过文件中的空行,避免无效解析
            if (line.isEmpty()) {
                continue;
            }

            if (lineNumber == 1) {
                // 解析第一行的棋盘尺寸
                try {
                    size = Integer.parseInt(line);
                    System.out.println("读取到棋盘尺寸:" + size);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException("文件第一行必须是有效的整数(棋盘尺寸)", e);
                }
                lineNumber++;
                continue;
            }

            // 处理后续的舰船数据行
            String[] parts = line.split(";");
            if (parts.length < 2) {
                System.err.println("无效的舰船行格式,跳过该行:" + line);
                lineNumber++;
                continue;
            }

            String shipName = parts[0].trim();
            // 初始化坐标数组:长度为parts.length-1(第一个元素是船名),每个子数组存x、y坐标
            int[][] coordinates = new int[parts.length - 1][2];

            for (int i = 1; i < parts.length; i++) {
                String coordStr = parts[i].trim();
                // 解析坐标字符串,比如"(3,2)" -> 提取出3和2
                try {
                    // 去掉前后括号,拆分x和y值
                    String[] xy = coordStr.replaceAll("[()]", "").split(",");
                    int x = Integer.parseInt(xy[0].trim());
                    int y = Integer.parseInt(xy[1].trim());
                    coordinates[i - 1][0] = x;
                    coordinates[i - 1][1] = y;
                } catch (Exception e) {
                    throw new IllegalArgumentException("坐标格式错误:" + coordStr, e);
                }
            }

            // 将舰船和对应坐标存入映射
            shipCoordinates.put(shipName, coordinates);
            System.out.println("读取到舰船:" + shipName + ",坐标数量:" + coordinates.length);
            lineNumber++;
        }
        scanner.close();
    }

    // 提供getter方法让外部获取读取到的数据
    public int getSize() {
        return size;
    }

    public Map<String, int[][]> getShipCoordinates() {
        return shipCoordinates;
    }

    // 测试用例,验证读取功能
    public static void main(String[] args) {
        try {
            BattleshipFileReader reader = new BattleshipFileReader();
            reader.ReadFile(new File("battleship_data.txt"));

            // 打印读取结果
            System.out.println("\n=== 读取结果汇总 ===");
            System.out.println("棋盘尺寸:" + reader.getSize());
            for (Map.Entry<String, int[][]> entry : reader.getShipCoordinates().entrySet()) {
                System.out.print(entry.getKey() + " 的坐标:");
                for (int[] coord : entry.getValue()) {
                    System.out.print("(" + coord[0] + "," + coord[1] + ") ");
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
关键细节说明
  • 棋盘尺寸处理:第一行字符串转为int类型,加入了格式校验,避免非数字输入导致程序崩溃。
  • 舰船存储:用HashMap<String, int[][]>关联船名和坐标数组,方便后续按船名快速查询对应坐标。
  • 坐标解析:对每个坐标字符串(比如(3,2)),先去除括号,再拆分x和y值,转为int后存入二维数组。
  • 异常处理:针对无效的行格式、坐标格式加入了异常抛出,方便调试时快速定位问题。
示例文件内容参考

假设你的battleship_data.txt内容如下:

10
Carrier;(3,2);(3,3);(3,4);(3,5);(3,6)
Battleship;(5,1);(5,2);(5,3);(5,4)
Destroyer;(7,7);(7,8);(7,9)

运行测试代码后,控制台会输出读取到的棋盘尺寸和所有舰船的坐标信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:54:30