मैं जावा गेम बनाना चाहता हूं। सबसे पहले कार्यक्रम खिलाड़ियों की संख्या के लिए पूछता है; उसके बाद, यह उनके नाम पूछता है। मैंने उनके नाम 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."
अद्यतन:
मैं मुख्य में ऐसा किया (जिगर जोशी का सुझाव के रूप में)
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());
}
और यह प्रिंट "स्कोर: 0 नाम: एक स्कोर: 4 नाम: एक" जब मैं खिलाड़ियों की दो नाम डाल "एक" और "बी" मुझे लगता है कि समस्या यहाँ है
name.put(k,new Player(name1.getName(),scr));
मैं अपने पिछले for
की "names_of_players" में नाम रख सकते हैं?
+1: या 'एंट्रीसेट() ';) –
+1 एंट्रीसेट() उचित है यदि आपको दोनों कुंजी और मूल्य की आवश्यकता है। इसके अलावा आप केवल मूल्यों (या कुंजी) पर सीधे पुनरावृत्त कर सकते हैं। – viktor
@viktor अच्छा बिंदु। बढ़ाया उत्तर –