简体   繁体   中英

How do I get rid of a java.lang.NullPointerException error?

I am writing two classes, one for Store, and one Item class for an assignment. I submit it online and it auto-grades according to an unknown tester.

I get the error: java.lang.NullPointerException

I assume it has something to do with returning null, however I was told to return null in one of the methods. If anyone can teach me what it is and how to fix it, thatd be great!

    import java.util.ArrayList;
import java.util.Scanner;

public class Store {
    private ArrayList<Item> inventory;

    // CONSTRUCTORS

    /*
     * Constructs a store without any items in its inventory.
     */
    public Store() {

    }

    /*
     * Constructs a store by reading items from a given Scanner. The constructor
     * must repeatedly (until item name is *) read items from the given scanner
     * object and add it to its inventory. Here is an example of the data (that
     * has three items) that could be entered for reading from the supplied
     * scanner:
     */
    public Store(Scanner keyboard) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s1 = sc.nextLine();

            if (s1.equals("*")) {
                break;
            } else {
                Scanner ls = new Scanner(s1);
                while (ls.hasNext()) {
                    Item item = new Item(ls.next(), ls.nextInt(), ls.nextInt());
                    inventory.add(item);
                }
            }
        }
    }

    // MOTHODS

    /*
     * Finds an item by its name if it is part of the store's inventory Name is
     * case-insensitive Returns the Item object corresponding to the given name
     * if the item was found. If an item with the given name was not found, then
     * this method returns null.
     */
    public Item findItem(String name) {
        for (Item item : inventory) {
            if (item.getName().equalsIgnoreCase(name)) {
                return item;
            }
        }
        return null;
    }

    /*
     * Updates existing item or adds a new item to the inventory. If an item
     * with the same name as the given item already exists in the inventory,
     * then this method updates the quantity for the given item.
     */
    public void add(Item item) {
        for (Item items : inventory) {
            if (items.getName().equalsIgnoreCase(item.getName())) {
                items = item;
            } else {
                inventory.add(item);
            }
        }
    }

    /*
     * Performs operations reflecting selling an item from the store's
     * inventory. If the given item is not found in the inventory then this
     * method prints a message and returns null. If sufficient quantity of item
     * is not available then this method reports an error and returns null.
     * Otherwise (if the item is found and sufficient quantity is present in the
     * inventory) then this method removes the requested quantity from the
     * inventory and returns a new item that contains information about the item
     * purchased.
     */
    public Item sellItem(String name, int quantity) {
        for (Item items : inventory) {
            if (items.getName().equalsIgnoreCase(name)) {
                if (items.getQuantity() >= quantity) { // if name is equal and
                                                        // quantity is enough
                    @SuppressWarnings("unused")
                    Item ret = new Item(name, items.getUnitPrice(), quantity);
                    items.changeQuantity(-1 * (quantity));
                } else {// if name is there, but not enough quantity
                    System.out.println("Error: Found, but not enough quantity");
                    return null;
                }
            } else {
                System.out.println("Error: The item was not found.");
                return null;
            }
        }
        return null;
    }

    /*
     * Performs operations reflecting return of an item back to the store's
     * inventory. An item can only be returned to inventory if such an item
     * previously existed in the inventory. So, if you try to add bread to the
     * inventory, but there was never bread in the inventory in the first place,
     * then this method will not put the bread back on the shelf. If the given
     * item is not found in the inventory then this method prints a message and
     * returns false indicating the return was not accepted. Otherwise (if the
     * item is found) this method adds the returned quantity to the appropriate
     * item entry in its inventory and returns true.
     */
    public boolean returnItemToInventory(String name, int quantity) {
        for (Item items : inventory) {
            if (items.getName().equalsIgnoreCase(name)) { // if name exists
                items.changeQuantity(quantity); // adds quantity
                return true;
            } else { // it didnt exist
                System.out.println("ERROR: Never existed.");
                return false;
            }
        }
        return false;
    }

    /*
     * Returns a String representation of this store, consisting of a list of
     * all the store's inventory, and the net value (in dollars) of the store's
     * inventory. Formatting will be as shown in this example:
     */
    public String toString() {
        String ret = "";
        int re = 0;
        for (Item items : inventory) {
            ret += items.toString();
            re += items.getTotalPrice();
        }
        ret += "Net inventory price: " + re;
        return ret;
    }

}

You never initialized inventory .

public Store() {
    inventory = new ArrayList<Item>();
}

There could be other places where an NPE could occur. Please, next time tell us the exact line in your source where the exception occurs.

After running your code I got this

Exception in thread "main" java.lang.NullPointerException
    at swing7.Store.<init>(Store.java:36)
    at swing7.Store.main(Store.java:145)

which shows that inventory was clearly never instantiated:

private ArrayList<Item> inventory;

Easily fixed:

inventory = new ArrayList<Item>();

This is your problem:

public void add(Item item) {
    for (Item items : inventory) {
        if (items.getName().equalsIgnoreCase(item.getName())) {
            items = item;
        } else {
            inventory.add(item);
        }
    }
}

The first time you call this, inventory is still null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM