Iām trying to add Products to my OrderLine
(which is held by an Order) but when I try I get the NullPointerException
.
import java.util.*;
public class OrderLine;
private HashMap<Integer, Integer> products = new HashMap<Integer, Integer>();
//setter and getter for products
public void add(int productNbr, int amount) {
int newAmount = this.products.get(productNbr) + amount;
this.products.put(productNbr, newAmount);
}
And my Main-tester;
public class Main {
public static void main(String[] args) {
OrderLine ol = new OrderLine();
ol.add(1, 661);
ol.add(1, 5); //key 1 should hold value 666
System.out.println(ol.getProducts()); //Should print out {1, 666}
But all I get is "Exception in thread "main" java.lang.NullPointerException". I get the feeling that it works if I define/initiate the value before I add anything to it, but I shouldn't have to do that every time. Any ideas?
UPDATE: Fixed version;
public void add(int productNbr, int amount) {
if (this.products.get(productNbr) != null) {
int newAmount = this.products.get(productNbr) + amount;
this.products.put(productNbr, newAmount);
} else {
this.products.put(productNbr, amount);
}
}