繁体   English   中英

字符串数组值和HashMaps

[英]String Array Values and HashMaps

我一直在尝试通过使用HashMaps从配置文件中读取内容来区分房间属性与门属性来制作迷宫游戏。 如果我只打印String []值,它们将打印相应的配置值,但是,当我尝试通过HashMap的键调用它来打印值时,它告诉我该值为null。 有什么建议吗?

我的代码:

     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

您有System.out.println(roomSite.get(0)); 什么时候应该是System.out.println(roomSite.get("0"));

您的地图是从String映射到String[] ,而不是从Integer映射到String[]

另外,如果要获取更有意义的打印语句而不是[Ljava.lang.String;@e9e54c2 ,则可以使用Arrays.toString()方法。

在遍历文件之前初始化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")));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM