java - 如何根据二维数组“地图”制作二维坐标数组
问题描述
for 循环似乎错误地读取了我的列表。我怎样才能重写它以获得所需的输出?任何帮助或更正表示赞赏!
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;
}
使用:
public static void test2DArray(int[][] s){
for(int[] i : s){
for(int j : i){
System.out.print(j + " ");
}
System.out.print("\n");
}
}
要打印出来wallAt
,
我希望:
999 999
0 1
0 2
1 0
999 999
999 999
2 0
999 999
2 2
我得到什么:
0 2
999 999
2 2
0 0
0 0
0 0
0 0
0 0
0 0
解决方案
一切都很好,只是您的代码根本没有通过 array[2][1] 。您需要实现一个计数器,因为您已经从多维数组中制作了 2d 数组,并且 2d-array 应该分别采用 array[counter][0] 和 array[counter][1] 的形式,例如:
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;
}