简体   繁体   English

为什么我的应用程序会抛出 NullPointerException?

[英]Why is my application throwing a NullPointerException?

I am starting to work on three classes at once and while doing so i have received the error message above.我开始同时处理三个类,同时我收到了上面的错误消息。 I am very confused on why it is showing.我对它为什么显示感到非常困惑。 I'm new to java so it could be something very easy that i just can't see.我是 Java 新手,所以它可能是我看不到的非常简单的东西。 I am getting the error on the shopping cart class under the addToCart method.我在 addToCart 方法下的购物车类上收到错误。 I know this is alot of stuff to look at but i would really appreciate any and all help that i can get.我知道这是很多东西要看,但我真的很感激我能得到的任何帮助。

public class ShoppingCart
{
    private int itemCount;     //total number of items in the cart 
    private double totalPrice;     //total price of items in the cart 
    private final int MAXSIZE = 100; // cart maximum capacity 
    private Item[]cart;

    //creates an empty shopping cart 
    public ShoppingCart()
    {
       Item[]cart = new Item [MAXSIZE];
       itemCount = 0;
       totalPrice = 0.0;
    }

    //adds an item to the shopping cart
    public void addToCart(String itemName, double price, int quantity)
    {

        cart[itemCount] = new Item(itemName, price, quantity);
        totalPrice = (totalPrice + (quantity * price)); 
        itemCount++;

    }
    //returns the contents on the cart together with summary information
    public String toString()
    {
        String contents = "\nShopping Cart\n";
        contents = contents + String.format("%-12s%-12s%-10s%-7s%n", "Item",
        "Unit Price", "Quantity", "Item Total");

        for(int i = 0; i<itemCount; i++)
        contents = contents + cart[i].toString() + "\n";

        contents = contents + String.format("%20s$ %.2fn","CurrentTotal:", totalPrice);

        return contents;
    }

}













import java.util.*;

public class Shop
    {
    public static void main (String[] args)
    {
        ShoppingCart myCart = new ShoppingCart();
        Scanner kbd = new Scanner(System.in);




        String itemName;
        double itemPrice;
        int quantity;

        String keepShopping = "y";

        do 
        {
            System.out.print ("Enter the name of the item: "); 
            itemName = kbd.nextLine();

            System.out.print ("Enter the unit price: ");
            itemPrice = kbd.nextDouble();

            System.out.print ("Enter the quantity: ");
            quantity = kbd.nextInt();

            myCart.addToCart(itemName, itemPrice, quantity);

            System.out.print ("Continue shopping (y/n)? ");
            keepShopping = kbd.next();
            kbd.nextLine();
        }
        while (keepShopping.equals("y"));

        System.out.println("Have a Nice Day!");

    }
}










import java.text.NumberFormat;

public class Item
{
    private String name;
    private double unitPrice;
    private int quantity;

    // -------------------------------------------------------
    //  Create a new item with the given attributes.
    // -------------------------------------------------------
    public Item (String itemName, double itemPrice, int numPurchased)
    {
        name = itemName;
        unitPrice = itemPrice;
        quantity = numPurchased;
    }

    // -------------------------------------------------------
    //   Return a string with the information about the item
    // -------------------------------------------------------

    public String toString ()
    {
        return String.format("%-15s$%-8.2f%-11d$%-8.2f", name, unitPrice, quantity,     unitPrice*quantity);
    }

    // -------------------------------------------------
    //   Returns the unit price of the item
    // -------------------------------------------------
    public double getPrice()
    {
        return unitPrice;
    }

    // -------------------------------------------------
    //   Returns the name of the item
    // -------------------------------------------------
    public String getName()
    {
        return name;
    }

    // -------------------------------------------------
    //   Returns the quantity of the item
    // -------------------------------------------------
    public int getQuantity()
    {
        return quantity;
    }
}  

Here you aredeclaring the cart array在这里你声明cart数组

private Item[]cart;

inside this constructor, you are initializing it在这个构造函数中,你正在初始化它

public ShoppingCart()  {
   Item[]cart = new Item [MAXSIZE];
   itemCount = 0;
   totalPrice = 0.0;
}

but when you attempt to access one of its elements here ( cart[itemCount] ) it throws a NullPointerException但是当您尝试在此处访问其元素之一 ( cart[itemCount] ) 时,它会抛出NullPointerException

public void addToCart(String itemName, double price, int quantity)  {
    cart[itemCount] = new Item(itemName, price, quantity);
    totalPrice = (totalPrice + (quantity * price));
    itemCount++;
}

This is because, although you are declaring the array properly, it goes right back to null as soon as the constructor is over.这是因为,尽管您正确地声明了数组,但一旦构造函数结束,它就会立即返回null The scope of that instance is local to the constructor body itself.该实例的范围是构造函数体本身的局部范围

Change改变

Item[] cart = new Item [MAXSIZE];

to

cart = new Item [MAXSIZE];

Then,然后,

cart[itemCount] = new Item(itemName, price, quantity);

will no longer throw a NullPointerException , because cart 's scope has been expanded to the entire class.将不再抛出NullPointerException ,因为cart的范围已扩展到整个类。

You get the NullPointer exception if you are trying to reference a variable that has not been declared/instantiated.如果您尝试引用尚未声明/实例化的变量,则会出现 NullPointer 异常。 For instance if you declared something like: List newList;例如,如果您声明如下: List newList; Then tried doing: newList.add(item);然后尝试做: newList.add(item); It would thrown an exception because new list was never instantiated.它会抛出异常,因为从未实例化新列表。 If it is throwing it in the addToCart() function it is most likely because one of the variables you are using has not been declared or instantiated.如果它在 addToCart() 函数中抛出它,很可能是因为您正在使用的变量之一尚未声明或实例化。 I would debug and print out the value of each variable when you get to that function call to make sure they have a value associated with them.当您到达该函数调用时,我会调试并打印出每个变量的值,以确保它们具有与其关联的值。 If they don't that may just be your problem.如果他们不这样做,那可能只是你的问题。

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

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