I'm writing an inventory program for my Java class and I need some help. I've built an array of Item objects but when I try to reference the Item methods from that array, it gives me a nullpointerexception.
Here is the Inventory Class
Here is the Item class:
My professor has provided a test Class to be able to test the Inventory Class. Here it is also:
When I run the test class it passes the first few tests just fine, but when it tests my searchbycolorandname method, it throws out this error:
The 105 is just a remnant of my attempt to figure out why it's not working.
Any help would be greatly appreciated.
Here is the Inventory Class
import java.io.*;
import java.awt.*;
import java.util.*;
public class Inventory {
//TODO: Declare variables
private String[] text, values;
// public static Item[] products, search;
private int itemNumber = 0;
public static Item[] products = null;
public static Item[] search = null;
/**
* Read in data from input file and build an Inventory object.
*
* Reads the inventory data file and builds some sort of a collection of Items,
* one for each Item in the inventory data file. Keep in mind that addItem
* will want to later add an Item to the collection whose expansion must either
* be anticipated here or addressed in addItem. This constructor should handle
* malformed inventory records containing missing, extraneous or invalid data.
*
* @param input
* Scanner object bound to the inventory data file
*/
public Inventory(Scanner input) throws IOException {
// TODO: Complete the constructor, arranging for it to read the input
// file into some sort of a collection of Items.
// products = null;
while (input.hasNext())
{
products = new Item[itemNumber + 1];
products[itemNumber] = readItem(input, itemNumber);
itemNumber++;
}
}
/**
* @return An integer that denotes the number of items in the database.
*/
public int getDatabaseSize() {
int size = products.length;
return size;
}
/**
* Returns a reference to an Item[] containing the inventory of Items
*
* @return A reference to an Item array that contains the inventory.
*/
public Item[] getCompleteDatabase() {
// TODO: Return a reference to an Item[] containing the inventory.
return products;
}
/**
* Search the database for Items matching the given name and color.
*
* @param name
* A String that represents the item name.
* @param color
* The specified Color to be found
* @return An Item[] of matching Items or null if none.
*/
public Item[] searchByNameAndColor(String name, Color color) {
// TODO
// search = null;
Item[] temps = products.clone();
for (int i = 0; i < temps.length; i++)
{
Item it1 = temps[i];
System.out.println(temps.length);
String tempName = products[i].getName();
System.out.println(tempName);
Color tempColor = it1.getColor();
if (tempName.equalsIgnoreCase(name) && tempColor == color){
System.out.println("am i getting this far?");
search = new Item[i+1];
search[i] = temps[i];
}
}
return search;
}
/**
* Search the database for Items matching the given name.
*
* @param name
* A String that represents the item name.
*
* @return An Item[] of matching Items or null if none.
*/
public Item[] searchByName(String name) {
// TODO
for (int i = 0; i < products.length; i++)
{
String tempName = products[i].getName();
if (tempName.equalsIgnoreCase(name)){
search[i] = products[i];
}
}
return search;
}
/**
* Search the database for Items matching the given color name.
*
* @param name
* A String representing the color name (e.g. red)
* @return An Item[] of matching Items or null if none.
*/
public Item[] searchByColor(Color colorName) {
// TODO
for (int i = 0; i < products.length; i++)
{
Color tempColor = products[i].getColor();
if (tempColor == colorName){
search[i] = products[i];
}
}
return search;
}
/**
* Search the database for Items matching the given price. Prices are
* matched to within one cent.
*
* @param name
* A double that represents the price.
* @return An Item[] of matching Items or null if none.
*/
public Item[] searchByPrice(double price) {
// TODO
for (int i = 0; i < products.length; i++)
{
Double tempPrice = products[i].getPrice();
if (tempPrice == price){
search[i] = products[i];
}
}
return search;
}
/**
* Reads one line from an inventory data file containing the values
* representing an Item.
*
* @param input
* An object of type Get to read from a file or standard input.
* @param count
* The record number in the input stream that we will read.
* @return An Item or null
*/
private Item readItem(Scanner input, int count) throws IOException {
if (!input.hasNext())
return null;
String colorName = input.next();
//This section converts the First String input to a Color object
ColorNamer c1 = new ColorNamer(colorName);
Color color = c1.getAWTColor();
if (color == null) {
throw new IOException("\n Color not recognized in record #"
+ count);
}
if (!input.hasNext())
throw new IOException("\n No item name found in record #" + count);
String itemName = input.next();
int quantity;
try {
if (!input.hasNext())
throw new IOException("\n No item quantity found in record #"
+ count);
quantity = input.nextInt();
} catch (NumberFormatException e) {
throw new NumberFormatException(
"\n Expecting to read an integer in record #" + count);
}
double price;
try {
if (!input.hasNext())
throw new IOException("\n No item price found in record #"
+ count);
price = input.nextDouble();
} catch (NumberFormatException e) {
throw new NumberFormatException(
"\n Expecting to read a double in record #" + count);
}
Item nextItem = new Item(itemName, color, quantity, price);
return nextItem;
}
/**
* Print all the items in the database to the standard output for debugging.
*
*
*/
public void debugDumpDatabase() {
// TODO
}
/**
* Sorts the database
*
* Sorting is always in ascending order on a field determined by Item's
* compareMode variable.
*/
public void sortDatabase() {
// TODO: Consider using the sort method of the Java Arrays class.
}
/**
* Adds an Item to the inventory database
*
* @param item
* Item to be added to the database
*/
public void addItem(Item newItem) {
// TODO
}
} // Inventory
Here is the Item class:
import java.awt.Color;
import java.text.NumberFormat;
import examples.Person;
/**
* Stores the attributes of an item.
*
* @author Amit Jain
* @author Jim Conrad
* @author tjeffs
*/
public class Item implements Comparable<Item> {
private String name, colorName;
private Color color;
private int quantity;
private double price;
public enum CompareMode {
NAME, COLOR, PRICE
}
// public static final int COMPARE_NAME = 1;
// public static final int COMPARE_COLOR = 2;
// public static final int COMPARE_PRICE = 3;
private static CompareMode compareMode = CompareMode.NAME;
/**
* Builds an Item
*
* @param name
* Name of new item. Note: Space characters in the name will be
* replaced with underscore characters and removes uppercase.
* @param color
* Color of new item as defined in
* http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Color.html
* @param quantity
* Quantity of new item
* @param price
* Price of new item
*/
public Item(String name, Color color, int quantity, double price) {
this.name = cleanUp(name);
this.color = color;
this.quantity = quantity;
this.price = price;
}
/**
* Returns a String value of an Item for debugging
*/
public String toString() {
NumberFormat fmt = NumberFormat.getCurrencyInstance();
ColorNamer c1 = new ColorNamer(color);
String tabs = "\t\t", tabs2 = "\t\t";
if (name.length() >= 8){
tabs = "\t";
}
if (c1.getColorName().length() >= 8){
tabs2 = "\t";
}
String result = name + tabs + c1.getColorName() + tabs2 +
quantity + "\t" + String.format("%15s", fmt.format(price));
return result;
}
/**
* @param amount
* Added to quantity
*/
public void addToQuantity(int amount) {
quantity = quantity + amount;
}
/**
* @param amount
* If quantity>=amount, subtracts amount from quantity
*/
public void removeFmQuantity(int amount) {
if (quantity >= amount) {
quantity = quantity - amount;
}
}
/**
* @param newPrice
*/
public void setPrice(double newPrice) {
price = newPrice;
}
/**
* @param newQty
*/
public void setQuantity(int newQty) {
quantity = newQty;
}
/**
* @return Item name
*/
public String getName() {
return name;
}
/**
* @return Item Color
*/
public Color getColor() {
return color;
}
/**
* @return Item price
*/
public double getPrice() {
return price;
}
/**
* @return Item quantity
*/
public int getQuantity() {
return quantity;
}
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Item other) {
//TODO int compareTo(Item other) returns < 0 if Item precedes other, 0 if Item equals other, or > 0 if Item follows other.
int result = 0;
switch (compareMode) {
case NAME:
result = name.compareTo(other.name);
break;
case COLOR:
result = color.toString().compareTo(other.color.toString());
break;
case PRICE:
if (price < other.price){
result = -1;
} else if (price > other.price){
result = 1;
}
break;
}
return result;
}
/**
* @return the compareMode
*/
public static CompareMode getCompareMode() {
//TODO static void setCompareMode(int mode) specifies what fields are compared by method
// compareTo: Item.CompareMode.NAME, Item.CompareMode.COLOR, or Item.CompareMode.PRICE. The default compareMode is NAME.
return compareMode;
}
/**
* @param compareMode
* the compareMode to set
*/
public static void setCompareMode(CompareMode compareMode) {
Item.compareMode = compareMode;
}
/*
* Cleans illegal/invalid characters from an Item's name String
*
* Note: The encoding used to persist the database fields forbids using a
* space in an Item's name.
*
* @param name String to be cleaned of illegal/invalid characters.
*/
private String cleanUp(String name) {
name.toLowerCase();
return name.replaceAll(" ", "_");
}
}
My professor has provided a test Class to be able to test the Inventory Class. Here it is also:
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class InventoryTest extends AbstractTestFramework {
//The expected results for test file "data"
final private static String TEST_DATA_FILENAME="data2";
final private static int TEST_DATABASE_SIZE=105;
final private static int TEST_COUNT_RED_TABLES=1;
final private static int TEST_COUNT_TABLES=6;
final private static int TEST_COUNT_BLUE=16;
final private static int TEST_COUNT_PRICE_350=3;
final private static String TEST_SORTED_FIRST_NAME="airplane";
final private static double TEST_SORTED_FIRST_PRICE=2999.00;
final private static int TEST_SORTED_FIRST_QUANTITY=25;
/**
* @param args
*/
public static void main(String[] args) {
testConstructor();
testGetDatabaseSize();
testSearchByNameAndColor();
testSearchByName();
testSearchByColor();
testSearchByPrice();
testSortDatabase();
testAddItem();
System.out.println("InventoryTest passed");
System.exit(0);
}
private static void testConstructor() {
startTest();
Inventory db;
try {
db = new Inventory( new Scanner(new File(TEST_DATA_FILENAME)) );
assertNotNull(db);
} catch (FileNotFoundException e) {
System.out.println("File " + TEST_DATA_FILENAME + " not found");
failTest();
} catch (Exception e) {
e.printStackTrace();
failTest();
}
completeTest();
}
private static void testGetDatabaseSize() {
startTest();
Inventory db=null;
try {
db = new Inventory( new Scanner(new File(TEST_DATA_FILENAME)) );
assertNotNull(db);
} catch (FileNotFoundException e) {
System.out.println("File" + TEST_DATA_FILENAME + " not found");
failTest();
} catch (Exception e) {
e.printStackTrace();
failTest();
}
assertNotNull(db);
assertEquals(db.getDatabaseSize(),TEST_DATABASE_SIZE);
completeTest();
}
private static void testSearchByNameAndColor() {
startTest();
Inventory db=null;
try {
db = new Inventory( new Scanner(new File(TEST_DATA_FILENAME)) );
assertNotNull(db);
} catch (FileNotFoundException e) {
System.out.println("File" + TEST_DATA_FILENAME + " not found");
failTest();
} catch (Exception e) {
e.printStackTrace();
failTest();
}
Item result[] = db.searchByNameAndColor("table", Color.red);
assertNotNull(result);
assertEquals(result.length,TEST_COUNT_RED_TABLES);
completeTest();
}
private static void testSearchByName() {
startTest();
Inventory db=null;
try {
db = new Inventory( new Scanner(new File(TEST_DATA_FILENAME)) );
assertNotNull(db);
} catch (FileNotFoundException e) {
System.out.println("File" + TEST_DATA_FILENAME + " not found");
failTest();
} catch (Exception e) {
e.printStackTrace();
failTest();
}
Item result1[] = db.searchByName("table");
assertEquals(result1.length,TEST_COUNT_TABLES);
Item result2[] = db.searchByName("sans-quid-nominus"); //Non-existent name.
assertNull(result2);
completeTest();
}
private static void testSearchByColor() {
startTest();
Inventory db=null;
try {
db = new Inventory( new Scanner(new File(TEST_DATA_FILENAME)) );
assertNotNull(db);
} catch (FileNotFoundException e) {
System.out.println("File" + TEST_DATA_FILENAME + " not found");
failTest();
} catch (Exception e) {
e.printStackTrace();
failTest();
}
Item result[] = db.searchByColor("blue");
assertEquals(result.length,TEST_COUNT_BLUE);
completeTest();
}
private static void testSearchByPrice() {
startTest();
Inventory db=null;
try {
db = new Inventory( new Scanner(new File(TEST_DATA_FILENAME)) );
assertNotNull(db);
} catch (FileNotFoundException e) {
System.out.println("File" + TEST_DATA_FILENAME + " not found");
failTest();
} catch (Exception e) {
e.printStackTrace();
failTest();
}
Item result[] = db.searchByPrice(3.50);
assertEquals(result.length,TEST_COUNT_PRICE_350);
completeTest();
}
private static void testSortDatabase() {
startTest();
Inventory db=null;
try {
db = new Inventory( new Scanner(new File(TEST_DATA_FILENAME)) );
assertNotNull(db);
} catch (FileNotFoundException e) {
System.out.println("File" + TEST_DATA_FILENAME + " not found");
failTest();
} catch (Exception e) {
e.printStackTrace();
failTest();
}
db.sortDatabase();
Item items[] = db.getCompleteDatabase();
assertTrue(items[0].getName().equals(TEST_SORTED_FIRST_NAME));
assertEquals(items[0].getPrice(),TEST_SORTED_FIRST_PRICE);
assertEquals(items[0].getQuantity(),TEST_SORTED_FIRST_QUANTITY);
completeTest();
}
private static void testAddItem() {
startTest();
Inventory db=null;
try {
db = new Inventory( new Scanner(new File(TEST_DATA_FILENAME)) );
assertNotNull(db);
} catch (FileNotFoundException e) {
System.out.println("File" + TEST_DATA_FILENAME + " not found");
failTest();
} catch (Exception e) {
e.printStackTrace();
failTest();
}
Item item1 = new Item("foo zot",Color.blue,3,3.33); //Name has an illegal space
assertNotNull(item1);
db.addItem(item1);
Item item2[] = db.searchByName("foo_zot"); //Item name's space becomes an underscore.
assertNotNull(item2);
assertEquals(item2.length,1);
assertTrue(item2[0].getName().equals("foo_zot"));
assertEquals(item2[0].getPrice(),3.33);
assertEquals(item2[0].getQuantity(),3);
completeTest();
}
}
When I run the test class it passes the first few tests just fine, but when it tests my searchbycolorandname method, it throws out this error:
Starting testConstructor Completed testConstructor Starting testGetDatabaseSize Completed testGetDatabaseSize Starting testSearchByNameAndColor 105 Exception in thread "main" java.lang.NullPointerException at Inventory.searchByNameAndColor(Inventory.java:80) at InventoryTest.testSearchByNameAndColor(InventoryTest.java:84) at InventoryTest.main(InventoryTest.java:27)
The 105 is just a remnant of my attempt to figure out why it's not working.
Any help would be greatly appreciated.