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
答案 0 :(得分:0)
一切都很好,除了您根本不使用代码传递array [2] [1]。您需要实现一个计数器,因为您已经用多维数组制作了2d数组,而2d数组应分别采用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;
}