I'm using BlueJ to create an array. The array is of 10 objects inherited from another class.
Now, my problem is that every time I try to find an object within the array (using the findInventoryItem
, I get a java.lang.NullPointerException: null
error. Now the "inventoryItem" object comes from another class. I am using inventoryItems
as the actual array name. the objects that go into it are the inventoryItem
of class InventoryItem
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
/**
* THIS IS THE MODIFIED VERSION OF THE ARRAY LIST MANAGER CLASS
*
* @author RAGEED A BASRAWI
* @version VERSION 1
*/
public class HomeInventoryManagerARRAYClass
{
private InventoryItem inventoryItem;
private InventoryItem[] inventoryItems;
/**
* Initialise the home inventory manager.
*/
public HomeInventoryManagerARRAYClass()
{
InventoryItem inventoryItem;
inventoryItems = new InventoryItem[10];
}
/**
* Add an inventory item to the list.
*
*/
public void addInventoryItem(InventoryItem inventoryItem)
{
Random random = new Random();
inventoryItems[random.nextInt(9 - 0 + 1) + 0] = inventoryItem;
}
/**
* Try to find an inventory item in the inventory list with the given partNumber.
*
*/
public InventoryItem findInventoryItem(int partNumber)
{
for(int index = 0; index < 9; index ++)
{
if (inventoryItem.getPartNumber() == partNumber)
{
return inventoryItem;
}
if (inventoryItem.getPartNumber() != partNumber)
{
System.out.println("The entry " + partNumber + " does not exist. Pleast try again.");
}
}
return inventoryItem;
}
/**
* Locate an inventory item with the given partNumber, and return how
* many of this item are in inventory. If the partNumber does not
* match any item, return zero.
*/
public int numberInInventory(int partNumber)
{
InventoryItem inventoryItems = findInventoryItem(partNumber);
if(inventoryItems != null)//There aren't too many ways to write a statement to be NOT NULL. Its kind of annoying... -___-
{
return inventoryItems.getQuantity();
}
else
{
return 0;
}
}
/**
* Return the total number of items in inventory.
*
*/
public int numberInInventoryList()
{
return inventoryItems.length;
}
/**
* Print details of all the home inventory items.
*/
public void printInventoryList()
{
int index = 0;
while(index < inventoryItems.length)
{
System.out.println(inventoryItem = inventoryItems[index]);
index ++;
}
}
public int totalNumberInInventory()
{
int index = 0;
int absoluteInventory = 0;
while (index < inventoryItems.length)
{
InventoryItem inventoryItem = inventoryItems[index];
absoluteInventory += inventoryItem.getQuantity();
index ++;
}
return absoluteInventory;
}
}