문제

코디가 그렇게 정의되는 맵이 있습니다.

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

감사,
이삭 월러
(참고 - 숙제가 아닙니다)

도움이 되었습니까?

해결책

  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);
    }
    

다른 팁

포인트 클래스를 조정하거나 사용하기 위해 Tostring 메소드를 추가하는 것이 좋습니다.

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));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top