0

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

Edited by Usoda: n/a

2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by JamesCherrill
0
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;
   ...

Edited by JamesCherrill: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.