gpt4 book ai didi

java - 如何访问 HashMap 中的特定值?

转载 作者:太空宇宙 更新时间:2023-11-04 08:24:54 27 4
gpt4 key购买 nike

这个简单的游戏询问玩家的数量和他们的名字并计算他们的得分。我怎样才能找到得分最高的玩家?

主要:

  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));

最佳答案

您可以使用 Collections.max() 来获取通过 HashMap.entrySet() 获取的 hashmap 条目集合的最大值,并使用自定义比较器来比较值。

示例:

    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());
}
}));

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

关于java - 如何访问 HashMap 中的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8759717/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com