【问题标题】:Java fill int [][] array from property.fileJava从property.file填充int [] []数组
【发布时间】:2016-01-06 12:20:33
【问题描述】:

我想用 Java 编写一个 pacmanstyle 迷宫游戏。 对于迷宫,我使用的是属性文件,其中坐标以以下格式存储(即 x=1,y=5 -> 墙)为字符串:79,13=0 79,12=0 79,11=0

我想使用二维数组创建迷宫网格:int [][] maze。 我知道如何加载属性文件。然而,我的问题是,我不知道如何首先从属性中提取字符串变量,其次才是填充数组的正确方法。

public final class Labyrinth {

    private int i;
    private int j;
    private static int [][] maze;
    private String p;
    private String l;

    public void setMaze(int x, int y){
        x = this.i;
        y = this.j;
    }

    public static int[][] getMaze(){
        return maze;        
    }

    public Labyrinth(int rows, int cols) throws IOException{        
        try (FileInputStream in = new FileInputStream("level.properties")) {
            Properties p1 = new Properties();
            p1.load(in);
            p = p1.getProperty("Height");
            l = p1.getProperty("Width");

            cols = parseInt(p);
            rows = parseInt(l);
            maze = new int[rows][cols];

            for (i=0; i < rows; i++){
                for(j=0; j < cols; j++){
                    setMaze(parseInt(p1.getProperty('ValueX,ValueY')),
                            parseInt(p1.getProperty('ValueX,ValueY')));               
                }
            }        
        }
    }
}

任何有帮助的想法都将受到高度赞赏!

【问题讨论】:

    标签: java arrays properties


    【解决方案1】:

    我不知道如何首先从 .property 中提取字符串变量,其次才是填充数组的正确方法。

    提取字符串变量是什么意思?属性文件只是键值对的列表。在您的情况下,键是 x,y 并且值显然表示迷宫中的某个对象。

    您可以尝试像这样读取密钥:

    for (i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            int value = parseInt(p1.getProperty(i + "," + j); // Get the value of (i,j)
            maze[i][j] = value; // Assign the value to the maze
        }
    }
    

    【讨论】:

    • 非常感谢,有时候解决方法很明显,但我没看到:)
    • @bertvansneijder 请接受答案以表明您的问题已解决。
    • 对不起,第一次使用。
    猜你喜欢
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多