代码之家  ›  专栏  ›  技术社区  ›  Isaac Waller

X-Y坐标映射的Java字符串

  •  1
  • Isaac Waller  · 技术社区  · 17 年前

    我有一张地图,其中的坐标定义如下:

    class Coords {
            int x;
            int y;
            public boolean equals(Object o) {
                Coords c = (Coords)o;
                return c.x==x && c.y==y;
            }
            public Coords(int x, int y) {
                super();
                this.x = x;
                this.y = y;
            }
            public int hashCode() {
                return new Integer(x+"0"+y);
            }
        }
    

    (不是很好,我知道,请不要取笑我。)我现在如何创建一个字符串,其中的字符是从该映射映射映射的,例如:

    Map<Coords, Character> map = new HashMap<Coords, Character>();
    map.put(new Coords(0,0),'H');
    map.put(new Coords(1,0),'e');
    map.put(new Coords(2,0),'l');
    map.put(new Coords(3,0),'l');
    map.put(new Coords(4,0),'o');
    map.put(new Coords(6,0),'!');
    map put(new Coords(6,1),'!');
    somehowTransformToString(map); //Hello !
                                   //      !
    

    谢谢,
    艾萨克沃勒
    (注意-这不是家庭作业)

    2 回复  |  直到 16 年前
        1
  •  6
  •   Aaron Digulla    17 年前
    1. 创建一个比较器,可以按y和x对坐标进行排序:

      int d = c1.y - c2.y;
      if (d == 0) d = c1.x - c2.y;
      return d;
      
    2. 创建排序映射:

      TreeMap<Coords, Character> sortedMap = new TreeMap(comparator);
      sortedMap.putAll(map); // copy values from other map
      
    3. 按顺序打印地图的值:

      for (Character c: map.values()) System.out.print(c);
      
    4. 如果需要换行:

      int y = -1;
      for (Map.Entry<Coords, Character> e: map.entrySet()) {
          if (e.y != y) {
              if (y != -1) System.out.println();
              y = e.y;
          }
          System.out.print(c);
      }
      
        2
  •  1
  •   Peter Lawrey    17 年前

    我建议您将ToString方法添加到coord或使用Point类。

    Map<Point, Character> map = new HashMap<Point , Character>();
    map.put(new Point(0,0),'H');
    map.put(new Point(1,0),'e');
    map.put(new Point(2,0),'l');
    map.put(new Point(3,0),'l');
    map.put(new Point(4,0),'o');
    map.put(new Point(6,0),'!');
    map put(new Point(6,1),'!');
    String text = map.toString();
    

    如果要布局字符,可以使用多维数组。

    char[][] grid = new char[7][2];
    grid[0][0] ='H';
    grid[0][1] ='e';
    grid[0][2] ='l';
    grid[0][3] ='l';
    grid[0][4] ='o';
    grid[0][6] ='!';
    grid[1][6] ='!';
    for(char[] line: grid) System.out.println(new String(line));
    
    推荐文章