简体   繁体   English

如何摆脱java.lang.NullPointerException错误?

[英]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. 我正在编写两个类,一个用于存储,一个用于分配作业的Item类。 I submit it online and it auto-grades according to an unknown tester. 我在线提交,并且根据未知的测试人员自动对其评分。

I get the error: java.lang.NullPointerException 我收到错误: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. 我认为这与返回null有关,但是有人告诉我在一种方法中返回null。 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 . 您从未初始化过inventory

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

There could be other places where an NPE could occur. 可能会有其他地方发生NPE。 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: 这表明inventory显然从未实例化:

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. 首次调用时, inventory仍然为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java为什么会出现此错误? 线程“ main”中的异常java.lang.NullPointerException - Java Why do I get this error? Exception in thread “main” java.lang.NullPointerException 为什么在此代码中出现java.io.FileNotFoundException错误和java.lang.NullPointerException? - Why do I get a java.io.FileNotFoundException error and a java.lang.NullPointerException in this code? 实现适配器时出现错误java.lang.NullPointerException - I get the error java.lang.NullPointerException when implementing Adapters 我收到错误“ AWT-EventQueue-0” java.lang.NullPointerException,我不明白为什么在我的上下文中 - I get the error “AWT-EventQueue-0” java.lang.NullPointerException and i do not understand why in my context 在我的以下程序中摆脱java.lang.NullPointerException - get rid of java.lang.NullPointerException in my following program 如何修复java.lang.NullPointerException(android)? - How do I fix my java.lang.NullPointerException (android)? 我该如何解决这个 java.lang.NullPointerException? - how do i resolve this java.lang.NullPointerException? 我收到了错误java.lang.NullPointerException - I received Error java.lang.NullPointerException 我如何避免java.lang.NullPointerException错误 - How can i avoid java.lang.NullPointerException error 如何摆脱此java.lang.ArrayIndexOutOfBoundsException错误? - How do i get rid of this java.lang.ArrayIndexOutOfBoundsException error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM