java对hashmap迭代_java – 如何迭代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 name= new HashMap();

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> set = name.entrySet();

for (Map.Entry me : set)

{

System.out.println("Score :"+me.getValue().getScore() +" Name:"+me.getValue().getName());

}

并打印“得分:0名称:a得分:4名称:a”当我把两个名字的球员“a”和“b”。我认为问题在这里

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值