2012-01-06 7 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

マップのすべてのエントリを繰り返し処理し、各プレーヤーのスコアを取得する方法の例が既にあります。あなたは数値比較を行う方法を知らないのですか?あなたは何を試しましたか? –

+0

'p.getScore()'は何をしていますか? –

答えて

1

カスタムコンパレータのためにHashMap.entrySet()によって得られたハッシュマップエントリのコレクションの最大値を取得するためにCollections.max()を使用することができます値を比較する。

例:

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()'を使いたい場合は、 'values()'ではなく 'entrySet()'でそれを行う必要があり、カスタムコンパレータを書く必要があります。 –

+0

@MarkPeters:OPがプレイヤー名を望んでいないことがわかりました。 –

+0

@MarkPeters:今私は答えが儀式だと思います。 –

関連する問題