這個簡單的遊戲要求玩家人數和他們的名字,並計算他們的分數。我怎樣才能得到最高分的玩家?我如何訪問HashMap中的特定值?
主:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<String,Integer> players= new HashMap<String,Integer>();
System.out.printf("Give the number of the players: ");
int numOfPlayers = scanner.nextInt();
for(int k=1;k<=numOfPlayers;k++)
{
System.out.printf("Give the name of player %d: ",k);
String nameOfPlayer= scanner.next();
players.put(nameOfPlayer,0);//score=0
}
//This for finally returns the score
for(String name:players.keySet())
{
System.out.println("Name of player in this round: "+name);
//::::::::::::::::::::::
//::::::::::::::::::::::
int score=players.get(name)+ p.getScore();;
//This will update the corresponding entry in HashMap
players.put(name,score);
System.out.println("The Player "+name+" has "+players.get(name)+" points ");
}
}
這是我嘗試過自己:
Collection c=players.values();
System.out.println(Collections.max(c));
你已經有了一個如何遍歷地圖中所有條目的例子,並獲得每個玩家的分數。你不知道如何做數字比較?你有什麼嘗試過自己? – 2012-01-06 14:59:09
p.getScore()是做什麼的? – 2012-01-06 15:03:41