I have a Product class that is the parent of 3 other classes; Books, Movies, Music. And the Product class connects to the Store class that holds the Store's location.

If I need to find a certain Product I have to traverse the list of each the Store class and the Product class. However, my code is throwing a NullPointerExeption.

When I debug it shows that pHead = null.

I am thinking the error is within my addProductBook method and is not appointing the first product to head? Or my findProduct method holds the error.

My constructor and addProductBook is in my Store Class

public Store() {
		head = new Product(null, null, 0);
	}
public void addProductBook() {	
	if(head == null) {
			head = new Book(product, name, price, author, ISBN);
			return;
		}
		else {
			Book newBook = new Book(product, name, price, author, ISBN);
			while(newBook.getNext() != null) {
				newBook = (Book) newBook.getNext();

				newBook.setNext(newBook);
				Store.mainMenu();
			}
		}
}

getProduct()
returns product

getName() - String
returns name(Items name)

findProduct is in a different Class

public static void findProduct(String item) {
		Store current = head;
		Product pHead = current.getProduct();
                pHead.getName(); // This is a test spot that throws a NullPointerException
				
		while(pHead != null && current != null){
				if((pHead.getName().equals(item)))
				pHead.printProduct();
			
			else 
				current.getNextStore();
				pHead = pHead.getNext();
				}
head = new Product(null, null, 0);

Firstly, Product should be an abstract class - it makes no sense to create Product that you don't know whether it's a Book, Movie or Music
Secondly, you now have a dummy Product full of nulls at the head of your list, so a line like

pHead.getName().equals(...

is going to throw a NPE because getName() returns null on the very first entry.

and finally, another suggestion...

public void addProductBook() {
   ...
   head = new Book(product, name, price, author, ISBN);
   ...
   Book newBook = new Book(product, name, price, author, ISBN);

looks like you are using a lot of shared variables (product, name ...) and repeating code, neither of which is a good idea. Much better to make thiis method self-contained by passing in the Product to add as a parameter. This also allows you to have one method to add a Product, not three similar methods, one for each of the subclasses.

public void addProduct(Product p) {
   if(head == null) {
      head = p;
   ...
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.