2009-05-25 4 views
1

J'ai une carte où Coords est définie comme ceci:String Java à partir de Carte XY Coordonnées

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

(. Pas très bon, je sais, s'il vous plaît ne me taquine pas) Comment puis-je créer maintenant chaîne où les personnages sont mis en correspondance à partir de cette carte, par exemple:

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

Merci,
Isaac Waller
(note - ce n'est pas devoirs)

+0

Quelle est votre sortie? Console STD? –

+0

En fait, un contrôle de champ de texte. –

+0

(EditText sur Android) –

Répondre

6
  1. Créer un comparateur qui peut trier Coords par y et x:

    int d = c1.y - c2.y; 
    if (d == 0) d = c1.x - c2.y; 
    return d; 
    
  2. Créer une carte triée:

    TreeMap<Coords, Character> sortedMap = new TreeMap(comparator); 
    sortedMap.putAll(map); // copy values from other map 
    
  3. Imprimer les valeurs de la carte dans l'ordre:

    for (Character c: map.values()) System.out.print(c); 
    
  4. Si vous avez besoin de nouvelles lignes:

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

Cela fonctionne pour X, mais Y est ignoré. –

+0

Ce n'est pas addAll, c'est putAll –

+0

putAll(): Correction. Le comparateur va d'abord trier par Y. Si Y est le même pour deux caractères, ils seront triés par X. Donc je ne suis pas sûr de ce que vous voulez dire par "Cela fonctionne pour X". –

1

Je vous suggère d'ajouter une méthode toString à Coord ou utiliser la classe 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(); 

Si vous souhaitez mettre en page les caractères, vous pouvez utiliser un tableau multidimensionnel.

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)); 
Questions connexes