Reputation: 67
I'm getting the nullpointerexception in the line 9 (the one with a comment).
I'm trying to use the method as a parametre in the shoppingCart class:
import java.util.*;
public class ShoppingCart {
private Map<String, Purchase> ShoppingCart;
public void add (String product, int price) {
Purchase purchase = new Purchase(product, 1, price);
ShoppingCart.put(product, purchase); //this line doesn't work!
}
public int price() {
Collection<Purchase> total = shoppingCart.values();
}
}
The constructor for the Purchase method is:
public Purchase(String product, int amount, int price) {
The Main tries to add the product to the shoppingCart which causes the nullpointerexception:
ShoppingCart cart = new ShoppingCart();
cart.add("milk, 3);
I suppose I'm missing something fundamental when it comes to Maps. What am I doing wrong here?
Upvotes: 0
Views: 181
Reputation: 71
I think that the problem is that you don't initialize your shoppingCart:
private Map<String, Purchase> ShoppingCart= new HashMap<String,Purchase>()
Upvotes: 0
Reputation: 93167
You forgot to instantiate your map ShoppingCart = new HashMap<String, Purchase>()
.
By the way, in java, variables always start with a lower case letter (camelCase), only classes start with an upper case (PascalCase)
Upvotes: 1
Reputation: 24885
You never create a ShoppingCart
object. This is not like C++ in which the object is created when you define the variable; all variables are in fact references to objects and you need to explicity create the objects (with new
).
BTW, this line causes a compilation error (shoppingCart should be lowercase)
private Map<String, Purchase> ShoppingCart;
Upvotes: 0