Sofie Buur
Sofie Buur

Reputation: 45

Objects as keys in a HashMap - how to reference them (java)

I am currently working on a small project simulating a game. Each Player object has an inventory which is a HashMap<Item, Integer> where the Integer is the quantity of that Item.

I am currently trying to write a method in the Player class, that allows the player to buy an Item from a Shop, if the Player have enough Coins in their inventory. Each Player starts with 50 Coins in their inventory.

Although, when I am trying to acces the coins in the players inventory (using inventory.get(coins)), I get an "coins cannot be resolved to a variable error".

CONSTRUCTOR

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

METHOD THAT FAILS

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!");
        }
    }

I've tried instantiating the objects in the main method, although I get the same error. There must be something that I don't get regarding how to reference objects as keys in a HashMap... How else can I check if the player has enough coins? Thank you in advance!

Upvotes: 0

Views: 293

Answers (1)

egeorge
egeorge

Reputation: 682

You have declared coins as a local variable in the constructor.

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

So as soon as the constructor is complete, that variable goes away. You still have the object as a key in the map, but if you want to use the coins variable to look it up in the map, you have to declare it as a member (outside the constructor).

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

Upvotes: 1

Related Questions