bertvansneijder bertvansneijder - 3 months ago 16
Java Question

Java fill int [][] array from property.file

I want to program a pacmanstyle maze game in Java.
for the maze i am using a property file, in which coordinates are stored (i.e. x=1, y=5 -> wall) as strings in following format:

79,13=0 79,12=0 79,11=0
.

I want to create the mazegrid using a 2d array:
int [][] maze
.
i know how to load in a property file. My problem however is, I have no idea how to first extract the string variables out of the property and second the proper way to fill the array.

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')));
}
}
}
}
}


Any helpfull thought will be highly appreciated!

Answer

i have no idea how to first extract the string variables out of the .property and second the proper way to fill the array.

What do you mean by extracting string variables? A property file is simply a list of key-value pairs. In your case, the key is x,y and the value is apparently indicating some object in the maze.

You could try reading the keys like this:

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
    }
}