2011-12-27 34 views
25

Voglio fare un gioco Java. All'inizio il programma richiede il numero dei giocatori; dopo di ciò, chiede i loro nomi. Ho inserito i loro nomi in un HashMap con un ID e il loro punteggio. Alla fine del gioco conto il punteggio e voglio inserirlo nello HashMap (il punteggio specifico per il nome specifico). Qualcuno sa come fare questo? Questo è il mio codice:Come posso scorrere gli elementi in Hashmap?

giocatore:

public class Player { 

public Player() { 
} 

public void setScore(int score) { 
    this.score = score; 
} 

public void setName(String name) { 
    this.name = name; 
} 

private String name; 
private int score; 

public Player(String name, int score) { 
    this.name = name; 
    this.score = score; 
} 
public String getName() { 
    return name; 
} 

@Override 
public String toString() { 
    return "Player{" + "name=" + name + "score=" + score + '}'; 
} 

public int getScore() { 
    return score; 
} 

principale:

Scanner scanner = new Scanner(System.in); 
HashMap<Integer,Player> name= new HashMap<Integer,Player>(); 

    System.out.printf("Give the number of the players "); 
    int number_of_players = scanner.nextInt(); 


    for(int k=1;k<=number_of_players;k++) 
    { 


     System.out.printf("Give the name of player %d: ",k); 
     name_of_players= scanner.nextLine(); 
     name.put(k, new Player(name_of_players,0));//k=id and 0=score 

    } 


    //This for finally returns the score and   
    for(int k=1;k<=number_of_players;k++) 
    { 
     Player name1 = name.get(k); 
    System.out.print("Name of player in this round:"+name1.getName()); 
    .............. 
    ............. 
    int score=p.getScore(); 
    name.put(k,new Player(name1.getName(),scr));//I think here is the problem 

    for(int n=1;n<=number_of_players;n++)//prints all the players with their score 
     { 

    System.out.print("The player"+name1.getName()+" has "+name1.getScore()+"points"); 

     } 

Qualcuno sa come posso finalmente stampare ad esempio:

"The player Nick has 10 points. 
The player Mary has 0 points." 

Aggiornamento:

Ho fatto questo in main (come suggeriscono Jigar Joshi)

name.put(k,new Player(name1.getName(),scr)); 
Set<Map.Entry<Integer, Player>> set = name.entrySet(); 

for (Map.Entry<Integer, Player> me : set) 
{ 
System.out.println("Score :"+me.getValue().getScore() +" Name:"+me.getValue().getName()); 

} 

e la stampa "Risultato: 0 Nome: un Punteggio: 4 Nome: un" quando ho messo due nomi dei giocatori "a" e "b" .Io credo che il problema è qui

name.put(k,new Player(name1.getName(),scr)); 

Come posso mettere i nomi in "names_of_players" della mia precedente for?

risposta

49

bisogno chiave & Value in Iteration

Usa entrySet() per scorrere Map e la necessità di accedere il valore e la chiave:

Map<String, Person> hm = new HashMap<String, Person>(); 

hm.put("A", new Person("p1")); 
hm.put("B", new Person("p2")); 
hm.put("C", new Person("p3")); 
hm.put("D", new Person("p4")); 
hm.put("E", new Person("p5")); 

Set<Map.Entry<String, Person>> set = hm.entrySet(); 

for (Map.Entry<String, Person> me : set) { 
    System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge()); 

} 

punto chiave nella Iteration

Se si desidera solo per iterare keys della mappa è possibile utilizzare keySet()

for(String key: map.keySet()) { 
    Person value = map.get(key); 
} 

bisogno del valore in Iteration

Se si desidera solo per iterare su values della mappa è possibile utilizzare values()

for(Person person: map.values()) { 

} 
+1

+1: o 'entrySet()';) –

+4

+1 entrySet() è ragionevole se è necessario sia la chiave che il valore. Inoltre puoi scorrere direttamente solo su valori (o chiavi). – viktor

+0

@viktor bel punto. risposta migliorata –

3

Non si dovrebbe mappare il punteggio al giocatore. Si dovrebbe mappare giocatore (o il suo nome) di segnare:

Map<Player, Integer> player2score = new HashMap<Player, Integer>();

Quindi aggiungere giocatori per mappare: punteggio int = .... Calciatori = new Player(); player.setName ("John"); // ecc. player2score.mettere (giocatore, punteggio);

In questo caso il compito è banale:

int score = player2score.get(player);

3

Dal momento che tutti i giocatori sono numerate vorrei solo usare un ArrayList<Player>()

Qualcosa di simile

List<Player> players = new ArrayList<Player>(); 

System.out.printf("Give the number of the players "); 
int number_of_players = scanner.nextInt(); 
scanner.nextLine(); // discard the rest of the line. 

for(int k = 0;k < number_of_players; k++){ 
    System.out.printf("Give the name of player %d: ", k + 1); 
    String name_of_player = scanner.nextLine(); 
    players.add(new Player(name_of_player,0)); //k=id and 0=score 
} 

for(Player player: players) { 
    System.out.println("Name of player in this round:" + player.getName()); 
1
HashMap<Integer,Player> hash = new HashMap<Integer,Player>(); 
Set keys = hash.keySet(); 
Iterator itr = keys.iterator(); 

while(itr.hasNext()){ 
    Integer key = itr.next(); 
    Player objPlayer = (Player) hash.get(key); 
    System.out.println("The player "+objPlayer.getName()+" has "+objPlayer.getScore()+" points"); 
} 

È puoi utilizzare questo codice per stampare tutti i punteggi nel tuo formato.

Problemi correlati