我一直试图通过使用HashMaps从配置文件中读取以区分Room属性与Door属性来制作迷宫类型的游戏。如果我只是打印String []值,它们会打印相应的配置值,但是,当我尝试使用HashMap通过其键调用它来打印值时,它会告诉我值为空。 有什么建议吗?
我的代码:
while (file.hasNextLine()) {
String line = file.nextLine();
if (line.isEmpty()) {
continue;
}
Scanner scanner = new Scanner(line);
String type = scanner.hasNext() ? scanner.next() : "";
String name = scanner.hasNext() ? scanner.next() : "";
String wall1 = scanner.hasNext() ? scanner.next() : "";
String wall2 = scanner.hasNext() ? scanner.next() : "";
String wall3 = scanner.hasNext() ? scanner.next() : "";
String wall4 = scanner.hasNext() ? scanner.next() : "";
HashMap<String,String[]> roomSite = new HashMap<String, String[]>();
HashMap<String,String[]> doorSite = new HashMap<String, String[]>();
String[] options = new String[]{wall1,wall2,wall3,wall4};
if(type.equals("room")){
roomSite.put(name, options);
}else if(type.equals("door")){
doorSite.put(name, options);
}else{
System.out.println("Error in config file. Please check that all options are valid.");
}
System.out.println(roomSite.get(0));
System.out.println(doorSite.get("d0"));
}
输出:
null
null
null
null
null
null
null
[Ljava.lang.String;@e9e54c2
null
null
的config.ini
room 0 wall d0 wall wall
room 1 d0 wall d1 wall
room 2 wall wall wall d1
door d0 0 1 close
door d1 1 2 open
答案 0 :(得分:1)
如果System.out.println(roomSite.get(0));
System.out.println(roomSite.get("0"));
为String
您的地图从String[]
映射到Integer
,而不是String[]
到[Ljava.lang.String;@e9e54c2
。
此外,如果您想获得更有意义的打印语句而不是Arrays.toString()
,则可以使用{{1}}方法。
答案 1 :(得分:1)
在迭代文件之前初始化HashMaps
。尝试这样的事情:
public static void main(String []argh) throws FileNotFoundException
{
Scanner scan = new Scanner(new File("config.ini"));
HashMap<String, String[]> roomSite = new HashMap<>();
HashMap<String, String[]> doorSite = new HashMap<>();
while(scan.hasNext()){
String type = scan.next();
String name = scan.next();
String[] walls = scan.nextLine().trim().split(" ");
switch(type){
case "room":
roomSite.put(name, walls);
break;
case "door":
doorSite.put(name, walls);
break;
default:
System.out.println("Error in config file. Please check that all options are valid.");
}
}
System.out.println(Arrays.toString(roomSite.get("0")));
System.out.println(Arrays.toString(doorSite.get("d0")));
}