2012-01-06 11 views
1

这个简单的游戏要求玩家人数和他们的名字,并计算他们的分数。我怎样才能得到最高分的玩家?我如何访问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)); 
+3

你已经有了一个如何遍历地图中所有条目的例子,并获得每个玩家的分数。你不知道如何做数字比较?你有什么尝试过自己? – 2012-01-06 14:59:09

+0

p.getScore()是做什么的? – 2012-01-06 15:03:41

回答

1

您可以使用Collections.max()获得HashMap的条目由HashMap.entrySet()定制的比较对于所得到的集合的最大值比较值。

例子:

HashMap<String,Integer> players= new HashMap<String,Integer>(); 
    players.put("as", 10); 
    players.put("a", 12); 
    players.put("s", 13); 
    players.put("asa", 15); 
    players.put("asaasd", 256); 
    players.put("asasda", 15); 
    players.put("asaws", 5); 
    System.out.println(Collections.max(players.entrySet(),new Comparator<Entry<String, Integer>>() { 
     @Override 
     public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { 
      return o1.getValue().compareTo(o2.getValue()); 
     } 
    })); 

可以修改上面的代码以更好地满足您的条件。

+0

哪一个会让你获得最高分,但不是得分最高的玩家。如果你想使用'Collections.max()',你需要在'entrySet()'而不是'values()'上执行,你需要编写一个自定义比较器。 – 2012-01-06 15:00:18

+0

@MarkPeters:没有看到OP要玩家的名字。 – 2012-01-06 15:02:18

+0

@MarkPeters:现在我认为答案是礼仪。 – 2012-01-06 15:12:21