Sanny
Sanny

Reputation: 79

java storing instance variables and access using one of the key values

I am currently learning Java in uni and I encountered this problem:

public class simpleStockManager {
    private String sku;
    private String name;
    private double price;

    public void newItem(String sku, String name, double price) {
        this.sku = sku;
        this.name = name;
        this.price = price;
    }

    public String getItemName(String sku) {
        return name;
    }
}

I have declared a class and some instance variables and I try to access to items using sku. So if I declare 3 items in this order:

simpleStockManager sm = new simpleStockManager();
sm.newItem("1234", "Jam", 3.25);
sm.newItem("5678", "Coffee", 4.37);
sm.newItem("ABCD", "Eggs", 3.98);

When I try the getItemName method with sku == "5678" it should return "Coffee", but it's returning "Eggs". I think it is the latest declared item that overwrites the previous item but I don't know how to solve this. Any help will be appreciated.

Upvotes: 0

Views: 923

Answers (1)

Guillaume Barré
Guillaume Barré

Reputation: 4218

Each call to newItem changes the values of your instance variables.

You will always get the last values set by m.newItem("ABCD", "Eggs", 3.98);

If you wand to use sku as a key to store several variables you can use a Map

For example :

class SimpleStockManager{
    // The key of your map will be sku, 
    //and the name and the price can be for exemple in a Product class
    private HashMap<String, Product>  products = new HashMap<>();

    public void newItem(String sku, String name, double price){
        // A call to newItem will create a new Product and store it 
        products.put(sku, new Product(name, price));
    }

    public String getItemName(String sku){
        if (products.containsKey(sku)){
            return products.get(sku).getName();
        }else {
            return " Product not found...";
        }
    }
}

Upvotes: 2

Related Questions