The for loops appear to be reading my list incorrectly. How can I rewrite this to get to the desired output? Any help or corrections is appreciated!
public static String[][] map2 = {{"-","#","#"},
{"#","-","-"},
{"#","D","#"}};
public static int[][] readMap(String[][] map){
int[][] wallAt = new int[map.length * map[0].length][2];
for(int y = 0; y < map.length ; y++){
for(int x = 0; x < map.length; x++){
if(map[x][y].equals("#")){
wallAt[x][0] = x;
wallAt[x][1] = y;
}
else{
wallAt[x][0] = 999;
wallAt[x][1] = 999;
}
}
}
return wallAt;
}
Using:
public static void test2DArray(int[][] s){
for(int[] i : s){
for(int j : i){
System.out.print(j + " ");
}
System.out.print("\n");
}
}
To print out wallAt
,
I would expect:
999 999
0 1
0 2
1 0
999 999
999 999
2 0
999 999
2 2
What I get:
0 2
999 999
2 2
0 0
0 0
0 0
0 0
0 0
0 0
Everything is OK except that you didn't go pass array[2][1] at all with your code. What you need is to implement a counter, because you had made 2d array out of multidimensional-array, and 2d-array should be in the form array[counter][0] and array[counter][1] respectively, something like:
public static int[][] readMap(String[][] map){
int counter = 0;
int[][] wallAt = new int[map.length*map[0].length][2];
for(int x = 0; x < map.length ; x++){
for(int y = 0; y < map[x].length; y++){
if(map[x][y].equals("#")){
wallAt[counter][0] = x;
wallAt[counter][1] = y;
}
else{
wallAt[counter][0] = 999;
wallAt[counter][1] = 999;
}
counter++;
}
}
return wallAt;
}