You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java HashMap中获取最高分玩家?完善Bowling类getWinner方法

解决HashMap中找出最高分玩家的问题

要实现getWinner()方法,核心逻辑是遍历HashMap中的键值对,跟踪当前的最高分及对应的玩家姓名,最后输出获胜者。以下是具体实现步骤:

  • 初始化两个变量:maxScore(存储当前最高分,初始设为Integer.MIN_VALUE以覆盖所有可能的分数)和winnerName(存储当前最高分玩家姓名)。
  • 遍历HashMap的entrySet(),同时获取每个玩家的姓名和分数。
  • 对比当前玩家分数与maxScore,如果当前分数更高,更新maxScore和winnerName。
  • 遍历结束后,输出获胜者姓名。

完整代码实现

import java.util.*; 

public class Bowling {
    HashMap<String, Integer> players;
    Bowling() {
        players = new HashMap<String, Integer>();
    }
    public void addPlayer(String name, int p) {
        players.put(name, p);
    }
    
    void getWinner(){
        // 初始化最高分和获胜者姓名
        int maxScore = Integer.MIN_VALUE;
        String winnerName = "";
        
        // 遍历HashMap的键值对
        for (Map.Entry<String, Integer> entry : players.entrySet()) {
            String currentName = entry.getKey();
            int currentScore = entry.getValue();
            
            // 比较分数,更新最高分和获胜者
            if (currentScore > maxScore) {
                maxScore = currentScore;
                winnerName = currentName;
            }
        }
        
        // 输出获胜者
        System.out.println(winnerName);
    }
}

public class Program {
    public static void main(String[] args) {
        Bowling game = new Bowling();
        Scanner sc = new Scanner(System.in);

        for(int i=0;i<3;i++) {
            String input = sc.nextLine();
            String[] values = input.split(" ");
            String name = values[0];
            int points = Integer.parseInt(values[1]);
            game.addPlayer(name, points);
        }
        game.getWinner();
    }
}

补充说明

  • 如果存在多个玩家分数相同且都是最高分,上述代码会返回第一个遇到的最高分玩家。如果需要处理同分情况,可以根据需求修改逻辑(比如收集所有最高分玩家后输出)。
  • 使用Integer.MIN_VALUE作为初始最高分,确保即使所有玩家分数都是负数,也能正确找到最高分。

内容的提问来源于stack exchange,提问作者sammy sigey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:24:19