【问题标题】:Java String from Map of X-Y Coordinates来自 X-Y 坐标图的 Java 字符串
【发布时间】:2010-10-28 18:46:37
【问题描述】:

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

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 !
                               //      !

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

【问题讨论】:

  • 你的输出是什么?性病控制台?
  • 其实就是一个文本域控件。

标签: java string map coordinates coordinate-systems


【解决方案1】:
  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);
    }
    

【讨论】:

  • putAll():已修复。比较器将首先按 Y 排序。如果两个字符的 Y 相同,它们将按 X 排序。所以我不确定“这适用于 X”是什么意思。
  • 没有打印换行符。不过这还算不错,所以我会接受它。
  • 在这种情况下,将当前 Y 值保存在局部变量中,并使用地图的实体接口。当 Y 值改变时,打印一个换行符。
【解决方案2】:

我建议你在 Coord 中添加一个 toString 方法或者使用 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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-20
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2021-07-10
    相关资源
    最近更新 更多