gpt4 book ai didi

java - 如何将字符串从txt文件转换为java中的不同子字符串

转载 作者:行者123 更新时间:2023-12-03 23:14:12 25 4
gpt4 key购买 nike

所以我的类 LevelLoader 中有这个方法 loadLevel,我想读取文件并将其转换为 tilemap。这基本上是一个二维的 Tiles 数组。一个 tile 有 2 个参数:id 和 damage

文件看起来像这样:

00.05;00.05;00.04;02.03;
00.05;01.00;01.00;02.03;
00.05;01.00;01.00;02.04;
00.05;00.05;03.00;02.01;

第一个数字是id,第二个值是伤害。此级别有 4 行和 4 列。

目前,我的方法是这样的:

public TileMap loadLevel(String path){
Tile[][] tiles = new Tile[12][12];
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line = null;
int i = 0;
while ((line = br.readLine()) != null) {
for(int j = 0; j < line.length() / 6; j++){
int id = valueOf(line.substring(j*6, 2);
int damage = valueOf(line.substring(j*6 + 3, 2);
tiles[i][j].setTile(id, damage);
//this is where the error comes from
}
i++;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}

return new TileMap(tiles);
}

我使用 12 作为最大宽度和高度。当我尝试运行它时,我的 for 循环中出现 NullPointerException。我尝试了不同的方法来加载此文件,但找不到有效的方法。

任何人都可以解释为什么会发生这种情况并可能说出我应该做什么吗?感谢您阅读本文。

最佳答案

您还没有初始化 Tile 数组元素,只有数组。

为此,您需要使用以下习语:

tiles[outer index][inner index] = new Tile(); // assuming default no-args constructor

Object 的默认值为 null,您在其上调用 setTile,因此抛出 NullPointerException

关于java - 如何将字符串从txt文件转换为java中的不同子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35490550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com