如何遍历Hashmap中的元素?
我想做一个Java游戏。首先,程序要求玩家的数量。之后,它询问他们的名字。我将他们的名字放在HashMap
ID和分数中。在游戏结束时,我会计算分数,然后将其放在HashMap
(特定名称的特定分数)中。有谁知道如何做到这一点?这是我的代码:
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;
}
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");
}
有谁知道我最后如何打印,例如:
"The player Nick has 10 points. The player Mary has 0 points."
我主要是这样做的(正如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());
}
当我将球员的两个名字“ a”和“ b”放进去时,它会显示“分数:0名称:a分数:4名称:a”。我认为问题出在这里
name.put(k,new Player(name1.getName(),scr));
如何将名称放在上一个的“ names_of_players”中for
?
回答:
迭代中需要关键和价值
使用entrySet()
迭代通过Map
和需要访问值和键:
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());
}
迭代中需要密钥
如果您只想遍历keys
地图,可以使用keySet()
for(String key: map.keySet()) { Person value = map.get(key);
}
迭代需要价值
如果您只想遍历values
地图,可以使用values()
for(Person person: map.values()) {}
以上是 如何遍历Hashmap中的元素? 的全部内容, 来源链接: utcz.com/qa/406534.html