gpt4 book ai didi

java - 如何遍历 Hashmap 中的元素?

转载 作者:IT老高 更新时间:2023-10-28 21:22:08 27 4
gpt4 key购买 nike

我想做一个Java游戏。一开始程序会询问玩家的人数;之后,它会询问他们的姓名。我将他们的名字放在带有 ID 和他们的分数的 HashMap 中。在游戏结束时我计算分数,我想把它放在 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));

如何将名称放在我以前的 for 的“names_of_players”中?

最佳答案

迭代中需要键和值

使用 entrySet()遍历 Map 并需要访问 value 和 key:

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

}

迭代中需要 key

如果你只想遍历 map 的keys,你可以使用keySet()

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

迭代中需要值(value)

如果您只想遍历 map 的 values,您可以使用 values()

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

}

关于java - 如何遍历 Hashmap 中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8644176/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com