购物车 Java 应用程序 (addToCart)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18473130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:56:01  来源:igfitidea点击:

Shopping Cart Java Application (addToCart)

javaarraysclassobjectmethods

提问by JRW2252

I am doing a Java Application for a class and need help with errors that are coming up after running the app.

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

The app is supposed to allow the user to add an item to the shopping cart(item name, price, quantity). The user described item will be added to the shopping cart array, and then it will be printed out once it is successfully added.

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

The shopping cart has a max capacity of 5 items initially, but if the cart size is > 5, it will be increased + 3, via the increaseSize method.

购物车最初的最大容量为 5 件商品,但如果购物车尺寸 > 5,则通过 increaseSize 方法将其增加 + 3。

As stated below, I believe that the addToCart method is not adding the user described item to the cart. That is why it is a null value within the toString method.

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

So, I basically need help with the addToCart method. Please correct me if I am wrong. Thank you.

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

An output from running the app is as follows:

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

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

Below is the ShoppingCart Class.

下面是 ShoppingCart 类。

The toString method should not have any errors being produced, but I believe that the problem lies within the addToCart method.

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

Below is the Shop Main.

下面是主店。

The ArrayList is not in use at this time, but will be later once the toString errors are corrected.

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"));

    }
}

Below is the Item Class:

下面是项目类:

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

采纳答案by andersschuller

I believe the problem is caused by these two lines from addToCart():

我相信问题是由以下两行引起的addToCart()

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

Unless quantityis 0, this means cart[0]will never contain anything. In fact, whatever the value of quantity, you will be leaving that many gaps in cart(e.g. if quantityis 2, cart[0]and cart[1]will be null).

除非quantity0,这意味着cart[0]永远不会包含任何东西。事实上,无论 的值是多少quantity,您都会留下许多空白cart(例如,如果quantity是 2,cart[0]并且cart[1]将为空)。

Since an Itemalready includes the quantity, I believe you meant to do this:

由于Item已经包含数量,我相信您打算这样做:

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

This way the first item will be put in cart[0], the second in cart[1], and so on.

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

Another small piece of advice: if you are concatenating any object with a String, you don't need to call toString()on the object. Java will automatically call String.valueOf()on the object, which avoids a NullPointerExceptionbecause it returns the String "null"instead. In this case, it might have helped you debug the problem because you would have noticed the null String appearing in your output. You would have to change your code to the following:

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

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

回答by Julien

The problem lies both in your addToCart method. If you type this code:

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

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

The shopping cart will have the following attributes:

购物车将具有以下属性:

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

The problem is that addToCart only modify the "itemcount" element of the array cartwithout considering the number of element added. Moreover, cart[0] will stay at null forever. You should remplace theses lines itemCount += quantity; cart[itemCount] = temp;

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

by

经过

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

回答by Tobias Kremer

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

This code is broken. You try to add to cartat index itemCount. This will throw index out of bound execptions. basicly you increase the size of your cart to late.

此代码已损坏。您尝试在索引itemCount处添加到购物车。这将使索引超出绑定执行。基本上,您将购物车的大小增加到很晚。

This also causes a lot off empty places in your array. You do not add your next Itemat the next place of your arra but you jump quantityplaces ahead. This causes some of the values in your array to be null. This is most likly causing the NullPointerExceütionin toString().

这也会导致您的阵列中有很多空位。您不会在 arra 的下一个位置添加您的下一个项目,而是将数量提前。这会导致数组中的某些值为null。这是最likly导致NullPointerExceütion的toString()

For how to implement this self growing list. You might want to take a look at the class ArrayList that comes with the JDK.

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

there are some other points i want to point out:

还有一些我想指出的点:

  • google javaDocand use it instead of your own custom comments
  • replace your for-loopin toString()with a for-each-loop
  • google javaDoc并使用它代替您自己的自定义注释
  • 更换你的for循环的toString()的for-each循环