我想制作一个Java游戏.首先,程序会询问玩家的数量; 之后,它要求他们的名字.我把他们的名字放在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;
}
Run Code Online (Sandbox Code Playgroud)
主要:
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");
}
Run Code Online (Sandbox Code Playgroud)
有谁知道我怎么能最终打印例如:
"The player Nick has 10 points.
The player Mary has 0 points."
Run Code Online (Sandbox Code Playgroud)
更新:
我主要做了这个(正如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());
}
Run Code Online (Sandbox Code Playgroud)
它打印"得分:0名称:一个得分:4名称:一个",当我把两个名字的球员"a"和"b".我认为问题在这里
name.put(k,new Player(name1.getName(),scr));
Run Code Online (Sandbox Code Playgroud)
如何将名字放在我之前的"names_of_players"中for
?
Jig*_*shi 49
使用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());
}
Run Code Online (Sandbox Code Playgroud)
如果你只想迭代keys
地图,你可以使用keySet()
for(String key: map.keySet()) {
Person value = map.get(key);
}
Run Code Online (Sandbox Code Playgroud)
如果您只想迭代values
地图,则可以使用values()
for(Person person: map.values()) {
}
Run Code Online (Sandbox Code Playgroud)