【问题标题】:Shopping Cart Java Application (addToCart)购物车 Java 应用程序 (addToCart)
【发布时间】:2013-08-30 15:42:51
【问题描述】:

我正在为一个类做一个 Java 应用程序,需要帮助解决运行该应用程序后出现的错误。

该应用程序应该允许用户将商品添加到购物车(商品名称、价格、数量)。用户描述的商品会被添加到购物车数组中,添加成功后会打印出来。

购物车最初的最大容量为 5 件,但如果购物车大小 > 5,则会通过 increaseSize 方法增加 + 3。

如下所述,我相信 addToCart 方法不会将用户描述的商品添加到购物车中。这就是为什么它在 toString 方法中是空值的原因。

所以,我基本上需要有关 addToCart 方法的帮助。 如果我错了,请纠正我。谢谢你。

运行应用程序的输出如下:

run:
Enter the name of the item: a
Enter the unit price: 2
Enter the quantity: 2
Exception in thread "main" java.lang.NullPointerException
    at shop.ShoppingCart.toString(ShoppingCart.java:62)
    at java.lang.String.valueOf(String.java:2854)
    at java.io.PrintStream.println(PrintStream.java:821)
    at shop.Shop.main(Shop.java:49)
Java Result: 1

下面是 ShoppingCart 类。

toString 方法不应该产生任何错误,但我认为问题出在 addToCart 方法中。

// **********************************************************************
//   ShoppingCart.java
//
//   Represents a shopping cart as an array of items
// **********************************************************************
import java.text.NumberFormat;

public class ShoppingCart
{

    private Item[] cart;
    private int itemCount;      // total number of items in the cart
    private double totalPrice;  // total price of items in the cart
    private int capacity;       // current cart capacity

    // -----------------------------------------------------------
    //  Creates an empty shopping cart with a capacity of 5 items.
    // -----------------------------------------------------------
    public ShoppingCart()
    {

      capacity = 5;
      cart = new Item[capacity];
      itemCount = 0;
      totalPrice = 0.0;
    }

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

        Item temp = new Item(itemName, price, quantity);
        totalPrice += (price * quantity);
        itemCount += quantity;
        cart[itemCount] = temp;
        if(itemCount==capacity)
        {
            increaseSize();
        }
    }

    // -------------------------------------------------------
    //  Returns the contents of the cart together with
    //  summary information.
    // -------------------------------------------------------
    public String toString()
    {
      NumberFormat fmt = NumberFormat.getCurrencyInstance();

      String contents = "\nShopping Cart\n";
      contents += "\nItem\t\tUnit Price\tQuantity\tTotal\n";

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

      contents += "\nTotal Price: " + fmt.format(totalPrice);
      contents += "\n";

      return contents;
    }

    // ---------------------------------------------------------
    //  Increases the capacity of the shopping cart by 3
    // ---------------------------------------------------------
    private void increaseSize()
    {
        Item[] temp = new Item[capacity+3];
        for(int i=0; i < capacity; i++)
        {
            temp[i] = cart[i];
        }
        cart = temp; 
        temp = null;
        capacity = cart.length;
    }
}

下面是主商店。

此时 ArrayList 未使用,但稍后将在更正 toString 错误后使用。

package shop;

// ***************************************************************
//   Shop.java
//
//   Uses the Item class to create items and add them to a shopping
//   cart stored in an ArrayList.
// ***************************************************************

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

public class Shop
{
    public static void main (String[] args)
    {
      ArrayList<Item> cart = new ArrayList<Item>();

      Item item;
      String itemName;
      double itemPrice;
      int quantity;

      Scanner scan = new Scanner(System.in);

      String keepShopping = "y";
      ShoppingCart cart1 = new ShoppingCart();
      do
          {
            System.out.print ("Enter the name of the item: ");
            itemName = scan.next();

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

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

            // *** create a new item and add it to the cart
            cart1.addToCart(itemName, itemPrice, quantity);



            // *** print the contents of the cart object using println
            System.out.println(cart1);

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

    }
}

以下是物品类别:

package shop;

// ***************************************************************
//   Item.java
//
//   Represents an item in a shopping cart.
// ***************************************************************

import java.text.NumberFormat;

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

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

    // -------------------------------------------------------
    //   Return a string with the information about the item
    // -------------------------------------------------------
    public String toString ()
    {
      NumberFormat fmt = NumberFormat.getCurrencyInstance();

      return (name + "\t" + fmt.format(price) + "\t" + quantity + "\t"
            + fmt.format(price*quantity));
    }

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

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

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

【问题讨论】:

  • 第 62 行 ShoppingCart.java 是什么?
  • 指的是 ShoppingCart 类,第 62 行:contents += cart[i].toString() + "\n";

标签: java arrays class object methods


【解决方案1】:

我认为问题是由addToCart() 的这两行引起的:

itemCount += quantity;
cart[itemCount] = temp;

除非quantity0,否则这意味着cart[0] 将永远不会包含任何内容。事实上,无论quantity 的值是多少,您都会在cart 中留下很多空白(例如,如果quantity 为2,cart[0]cart[1] 将为空)。

由于Item 已经包含数量,我相信您是故意这样做的:

cart[itemCount] = temp;
itemCount += 1;

这样第一项将被放入cart[0],第二项将被放入cart[1],以此类推。

另外一条小建议:如果你用字符串连接任何对象,你不需要在对象上调用toString()。 Java 将自动在对象上调用String.valueOf(),这避免了NullPointerException,因为它返回字符串"null"。在这种情况下,它可能会帮助您调试问题,因为您会注意到输出中出现了空字符串。您必须将代码更改为以下内容:

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

【讨论】:

    【解决方案2】:

    问题在于您的 addToCart 方法。 如果您输入此代码:

    ShoppingCart shopcart= new ShoppingCart();
    shopcart.addToCart("foo", 3, 2);
    

    购物车将具有以下属性:

    totalPrice=6
    itemCount = 2;
    cart = { null, null, foo, null, null};
    

    问题是addToCart只修改了数组cart的“itemcount”元素,没有考虑添加的元素个数。 此外,cart[0] 将永远保持为空。 你应该替换这些行 itemCount += 数量; 购物车[itemCount] = temp;

    通过

    for ( int i =0 ; i<quantity;i++)
    {
         cart[itemCount+i] = temp;
    } 
    itemCount += quantity;
    

    【讨论】:

    • 我尝试了建议的行,它没有产生任何错误消息。然而,它为购物车的数组添加了太多的项目。基本上,如果我要求添加一个项目,数量为 3;它将以每次 3 的数量分别添加第 3 项。输入商品名称: ab 输入单价: 2 输入数量: 3 购物车 商品 单价 数量 总计 ab $2.00 3 $6.00 ab $2.00 3 $6.00 ab $2.00 3 $6.00 总价: $6.00 是否继续购物(y/n)?
    【解决方案3】:
    public void addToCart(String itemName, double price, int quantity)
    { 
    
        Item temp = new Item(itemName, price, quantity);
        totalPrice += (price * quantity);
        itemCount += quantity;
        cart[itemCount] = temp;
        if(itemCount==capacity)
        {
            increaseSize();
        }
    }
    

    此代码已损坏。您尝试在索引 itemCount 处添加到 cart。这会将索引抛出边界异常。基本上,您将购物车的大小增加到晚。

    这也会导致数组中出现很多空位。您不会将下一个 Item 添加到您的 arra 的下一个位置,但您会向前跳 quantity 个位置。这会导致您的数组中的某些值为 null。这很可能导致 toString() 中的 NullPointerExceütion

    关于如何实现这个自我增长的列表。您可能想看看 JDK 附带的类 ArrayList。

    还有几点我想指出:

    • google javaDoc 并使用它来代替您自己的自定义 cmets
    • toString() 中的 for-loop 替换为 for-each-loop

    【讨论】:

    • 感谢您的意见。实际上这是一个由两部分组成的项目,使用 ArrayList 是第二部分。
    猜你喜欢
    • 2011-05-24
    • 2010-11-21
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    相关资源
    最近更新 更多