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
?
+1: o 'entrySet()';) –
+1 entrySet() è ragionevole se è necessario sia la chiave che il valore. Inoltre puoi scorrere direttamente solo su valori (o chiavi). – viktor
@viktor bel punto. risposta migliorata –