简体   繁体   中英

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. I am getting the error on the shopping cart class under the addToCart method. 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

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

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. 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.

You get the NullPointer exception if you are trying to reference a variable that has not been declared/instantiated. For instance if you declared something like: List newList; Then tried doing: 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. 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.

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