使用.txt
File 初始化2D对象数组。
JAVA [代码编辑](在2D对象数组中添加对象)
我正在从(txt
)文件创建一个Grid ,我想在2D Array中初始化它。
我已经阅读了很多关于这个问题的主题,但我没有找到可以提供帮助的内容
例如,这是2d数组,当我在b
这里读取字母时,应该将一个对象保存在(index [0,0])中。
到目前为止,我只能打印.txt
文件的内容,但我现在不知道如何添加对象。
public class MAP {
public static void main(String[] args) {
Grid[][] StreetCells = new Grid[40][30];
int x=0, y=0;
InputStream input = Main.class.getResourceAsStream("Grid.txt");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
String line;
// Read new lines until readLine() returns null
while ((line = reader.readLine()) != null) {
String[] values = line.split(",");
for (String str : values)
{
if (line.contains("*")){
StreetCells [x][y] = new Field();
}
if(line.contains("S")){
StreetCells [x][y] = new Street();
}
if(line.contains("B")){
StreetCells [x][y] = new BBuilding();
}
if(line.contains("b")){
StreetCells [x][y] = new SBuilding();
}
Grid str_grid = Grid.Double(str);
StreetCells[x][y]=str_grid;
System.out.println(StreetCells[x][y]);
y=y+1;
}
x=x+1;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
我想初始化对象的2D数组,以便在b
读取字母时,所以这里应该像示例(建筑物)这样的对象保存在数组中。
发布于 2019-05-16 11:12:48
如果使用此代码编辑帖子。
public class MAP {
public static void main(String[] args) {
Grid[][] StreetCells = new Grid[40][30];
int x=0, y=0;
InputStream input = Main.class.getResourceAsStream("Grid.txt");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
String line;
// Read new lines until readLine() returns null
while ((line = reader.readLine()) != null) {
String[] values = line.split(",");
for (String str : values)
{
if (line.contains("*")){
StreetCells [x][y] = new Field();
}
if(line.contains("S")){
StreetCells [x][y] = new Street();
}
if(line.contains("B")){
StreetCells [x][y] = new BBuilding();
}
if(line.contains("b")){
StreetCells [x][y] = new SBuilding();
}
Grid str_grid = Grid.Double(str);
StreetCells[x][y]=str_grid;
System.out.println(StreetCells[x][y]);
y=y+1;
}
x=x+1;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
https://stackoverflow.com/questions/-100006735
复制相似问题