如何根据二维数组制作坐标的二维数组"map"
How to make a 2D array of coordinates based on a 2D array "map"
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]。你需要的是实现一个计数器,因为你已经从多维数组中创建了二维数组,而二维数组应该分别采用 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;
}
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]。你需要的是实现一个计数器,因为你已经从多维数组中创建了二维数组,而二维数组应该分别采用 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;
}