繁体   English   中英

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

[英]Why is my application throwing a NullPointerException?

我开始同时处理三个类,同时我收到了上面的错误消息。 我对它为什么显示感到非常困惑。 我是 Java 新手,所以它可能是我看不到的非常简单的东西。 我在 addToCart 方法下的购物车类上收到错误。 我知道这是很多东西要看,但我真的很感激我能得到的任何帮助。

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;
    }
}  

在这里你声明cart数组

private Item[]cart;

在这个构造函数中,你正在初始化它

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

但是当您尝试在此处访问其元素之一 ( cart[itemCount] ) 时,它会抛出NullPointerException

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

这是因为,尽管您正确地声明了数组,但一旦构造函数结束,它就会立即返回null 该实例的范围是构造函数体本身的局部范围

改变

Item[] cart = new Item [MAXSIZE];

cart = new Item [MAXSIZE];

然后,

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

将不再抛出NullPointerException ,因为cart的范围已扩展到整个类。

如果您尝试引用尚未声明/实例化的变量,则会出现 NullPointer 异常。 例如,如果您声明如下: List newList; 然后尝试做: newList.add(item); 它会抛出异常,因为从未实例化新列表。 如果它在 addToCart() 函数中抛出它,很可能是因为您正在使用的变量之一尚未声明或实例化。 当您到达该函数调用时,我会调试并打印出每个变量的值,以确保它们具有与其关联的值。 如果他们不这样做,那可能只是你的问题。

暂无
暂无

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

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