【问题标题】:Objects as keys in a HashMap - how to reference them (java)对象作为 HashMap 中的键 - 如何引用它们 (java)
【发布时间】:2022-12-31 08:37:11
【问题描述】:

我目前正在做一个模拟游戏的小项目。每个Player 对象都有一个库存,它是一个HashMap<Item, Integer>,其中整数是该项目的数量。

我目前正在尝试在 Player 类中编写一个方法,如果玩家的库存中有足够的 Coins,它允许玩家从 Shop 购买 Item。每个 Player 的库存中都以 50 Coins 开头。

虽然,当我试图访问玩家库存中的硬币时(使用inventory.get(coins)),我得到一个“硬币无法解析为变量错误”。

构造函数

private String name;
    private HashMap<Item, Integer> inventory;
    private String location;


public Player (String name){
        this.name = name;
        location = "Home";

        inventory = new HashMap<>();

        Resource coins = new Resource("Coins", 1, 1);
        Tool pickaxe = new Tool("Pickaxe", 100, 100);
        Tool axe = new Tool("Axe", 100, 100);
        Tool shovel = new Tool("Shovel", 100, 100);
        Crop turnip = new Crop("Turnip", 20, "Spring");

        this.inventory.put(coins, 50);
        this.inventory.put(pickaxe, 1);
        this.inventory.put(axe, 1);
        this.inventory.put(shovel, 1);
        this.inventory.put(turnip, 10);
    }

失败的方法

public void buyItemPierre(Shop pierres, Item item){
        if (location.equals("Pierres")){

            if (pierres.getForSale().containsKey(item)){
                
                if (inventory.get(**coins**) >= pierres.getForSale().get(item)){ // ERROR HERE

                }
            }
            else{
                System.out.println("Sorry, that item is not for sale here");
            }

        }
        else{
            System.out.println("You have to visit Pierres before you can buy anything from there!");
        }
    }

我已经尝试在 main 方法中实例化对象,但我得到了同样的错误。关于如何将对象引用为 HashMap 中的键,肯定有一些我不明白的事情……我还能如何检查玩家是否有足够的coins?先感谢您!

【问题讨论】:

  • 这可以通过适当使用变量来解决,但老实说:不要。不要使用像它们这样的对象作为映射键。他们不会给你带来任何好处。使用静态的东西,如字符串“硬币”或自己的枚举。更加灵活。

标签: java hashmap


【解决方案1】:

您已在构造函数中将 coins 声明为局部变量。

        Resource coins = new Resource("Coins", 1, 1);

因此,一旦构造函数完成,该变量就会消失。你还有目的作为映射中的键,但是如果您想使用coins变量在映射中查找它,则必须将其声明为成员(在构造函数之外)。

private Resource coins= new Resource("Coins", 1, 1);

【讨论】:

  • 啊好吧,这确实有道理!但是我怎样才能将一个新对象添加到清单中并在以后访问它呢?那么我是否也应该将其声明为会员?
  • 就像您有一个 buyItemPierre 方法一样,您需要一个 addItem 方法,以便您可以向地图添加项目。
  • 另外:您使用的地图类型也称为“multiset”或“bag”:en.wikipedia.org/wiki/Multiset
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多