Tôi muốn tạo một trò chơi Java. Lúc đầu chương trình yêu cầu số lượng người chơi; sau đó, nó yêu cầu tên của họ. Tôi đặt tên của họ trong một số HashMap
với một ID và điểm số của họ. Vào cuối trò chơi tôi đếm số điểm và tôi muốn đặt nó trong số HashMap
(điểm cụ thể cho tên cụ thể). Có ai biết cách để làm điều này không? Đây là mã của tôi:Làm cách nào tôi có thể lặp qua các phần tử trong Hashmap?
Player:
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;
}
chính:
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");
}
Có ai biết làm thế nào tôi có thể cuối cùng in ví dụ:
"The player Nick has 10 points.
The player Mary has 0 points."
Cập nhật:
Tôi đã làm điều này trong main (như Jigar Joshi đề nghị)
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());
}
và nó in "Điểm: 0 Tên: Điểm: 4 Tên: a" khi tôi đặt hai tên người chơi "a" và "b" .Tôi nghĩ rằng vấn đề là ở đây
name.put(k,new Player(name1.getName(),scr));
Làm thế nào tôi có thể đặt tên trong "names_of_players" của trước for
của tôi?
+1: hoặc 'entrySet()';) –
+1 entrySet() là hợp lý nếu bạn cần cả khóa và giá trị. Ngoài ra, bạn có thể lặp trực tiếp qua các giá trị (hoặc các khóa). – viktor
@viktor điểm tốt đẹp. câu trả lời nâng cao –