【问题标题】:How to make a 2D array of coordinates based on a 2D array "map"如何根据二维数组“地图”制作二维坐标数组
【发布时间】:2019-04-03 23:18:21
【问题描述】:

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  

【问题讨论】:

  • 什么是 D,这里 test2array 方法的目的是什么? @GabeGalyon
  • 我建议学习如何在 IDE 中使用调试器。
  • 非“#”相对不重要,“D”代表门,尚未实际实现。 @MS90
  • 提供了 test2DArray 以防我在那里犯了错误,而不是在 readMap 中。 test2Darray 只是我用来打印 wallAt 以检查其内容的一种方法。 @MS90
  • 错误在readMap方法中。要了解它是什么,请使用此方法应该执行的操作更新您的帖子。换句话说,你为什么期望结果是999...

标签: java multidimensional-array coordinate-systems


【解决方案1】:

除了您的代码根本没有传递 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;                                             
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 2020-03-09
    相关资源
    最近更新 更多