【问题标题】:Comparing hashmap key values with an int将 hashmap 键值与 int 进行比较
【发布时间】:2018-03-19 02:48:05
【问题描述】:

我正在尝试为具有用户默认得分值的游戏编写 if 语句。我想将键的值(高分)与该用户的默认分数进行比较。如果分数高于他们的高分,那么我会将其“放入”地图中。

 if (map.containsKey(username)) 
 {
    System.out.println("Score for " + username + " is already present");

    if (map.get(highscore) > score) 
    {
      map.put(name, highscore);
    }
 }

如何修复这个内部 if 语句?

【问题讨论】:

  • 地图的关键是username,对吧?那么你期望get(highscore) 做什么呢?现在考虑一下,然后再试一次,例如scorehighscoreget(username)返回的值有什么区别?

标签: java hashmap compare


【解决方案1】:

根据你的描述,我猜map的值是highscore,下面是代码

    if (map.containsKey(username))
    {
        System.out.println("Score for " + username + " is already present");

        if (map.get(username) < score)
        {
            map.put(username, score);
        }
    }

【讨论】: