【发布时间】:2016-11-23 18:29:04
【问题描述】:
我目前正在尝试通过将文件加载到数组中来从文件中加载“地图”。我可以在没有数组的情况下打印文件本身,但我的项目是制作一个基于 ASCII 的游戏,所以我需要有坐标来放置其他对象。
import java.io.*;
public class Map
{
private static String mapFile = "";
private static File currentMap;
private static BufferedReader br;
private static int width;
private static int height;
char[][] map;
public Map(String newMap) throws IOException
{
int c;
char mapPiece;
mapFile = newMap;
currentMap = new File(mapFile);
try{
br = new BufferedReader(new FileReader(currentMap));
String line;
width = 0;
height = 0;
while((line = br.readLine()) != null)
{
height++;
width = line.length();
}
map = new char[width][height];
br.close();
br = new BufferedReader(new FileReader(currentMap));
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
if((c = br.read()) != -1)
map[x][y] = (char) c;
}
}
br.close();
} finally {}
System.out.println();
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
System.out.print(map[x][y]);
}
System.out.println();
}
}
}
当它返回输入时,地图完全是乱序的,没有任何意义。它应该看起来像:
#########################
#.......................#
#......#................#
########................#
#......#................#
#......#................#
#......#................#
#.######................#
#.......................#
#########################
但是看起来像:
##########
##########
#####
#..
..........
..........
.#
#.....
.#........
........#
########.
..........
.....#
#.
.....#....
..........
..#
#....
..#.......
.........#
#......#
..........
......#
#
.######...
..........
...#
#...
..........
..........
#
#######
我最初有它,其中 for 循环被包裹在一个 while 循环中,但当然它只打印了“#”符号。我只需要它来打印地图并将字符正确保存到数组中。
【问题讨论】:
-
您可以更改文件的格式吗?例如,你能不能让文件的第一行告诉你地图的宽度和高度是多少?
-
我可以,但是 ' while((line = br.readLine()) != null) { height++;宽度 = line.length(); }' 使高度和宽度由地图本身确定(以防大小发生变化)
-
你没有回答我的问题。
-
你负责地图文件吗?如,您是否允许在顶部添加一条指定宽度和高度的线?或者这是地图文件必须保持不变的某种家庭作业。
-
我建议在顶部添加一条线,指定宽度和高度。您两次读取文件是非常丑陋的,第一次只是为了计算高度。
标签: java arrays io bufferedreader