Votre panier Java Application (addToCart)


Je fais une application Java pour une classe et j'ai besoin d'aide avec les erreurs qui apparaissent après l'exécution de l'application.

L'application est censée permettre à l'utilisateur d'ajouter un article à votre panier(nom du produit, prix, quantité). L'article décrit par l'utilisateur sera ajouté au tableau de panier, puis il sera imprimé une fois qu'il aura été ajouté avec succès.

Le panier a une capacité maximale de 5 articles initialement, mais si la taille du panier est > 5, il sera augmenté + 3, via le Méthode increaseSize.

Comme indiqué ci-dessous, je crois que la méthode addToCart n'ajoute pas l'article décrit par l'utilisateur au panier. C'est pourquoi il s'agit d'une valeur nulle dans la méthode toString.

Donc, j'ai essentiellement besoin d'aide avec la méthode addToCart. S'il vous plaît corrigez-moi si je me trompe. Merci.

Le résultat de l'exécution de l'application est la suivante:

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

Ci-dessous est la classe ShoppingCart.

La méthode toString ne devrait pas avoir d'erreurs produites, mais je croyez que le problème réside dans la méthode 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;
    }
}

Ci-dessous est le magasin principal.

L'ArrayList n'est pas utilisée pour le moment, mais le sera plus tard une fois les erreurs toString corrigées.

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

    }
}

Ci-dessous est la classe d'élément:

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;
    }
} 
Author: JRW2252, 2013-08-27

3 answers

Je crois que le problème est causé par ces deux lignes de addToCart():

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

À moins que quantity ne soit 0, cela signifie que cart[0] ne contiendra jamais rien. En fait, quelle que soit la valeur de quantity, vous laisserez autant d'espaces dans cart (par exemple si quantity vaut 2, cart[0] et cart[1] seront nuls).

Étant donné qu'un Item inclut déjà la quantité, je crois que vous vouliez faire ceci:

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

De Cette façon, le premier élément sera mis en cart[0], le second dans cart[1], et ainsi de sur.

Un autre petit conseil: si vous concaténez un objet avec une chaîne, vous n'avez pas besoin d'appeler toString() sur l'objet. Java appellera automatiquementString.valueOf() sur l'objet, ce qui évite un NullPointerException car il renvoie la chaîne "null" à la place. Dans ce cas, cela pourrait vous avoir aidé à déboguer le problème car vous auriez remarqué que la chaîne null apparaissait dans votre sortie. Vous devrez changer votre code comme suit:

for (int i = 0; i < itemCount; i++)
    contents += cart[i] + "\n";
 2
Author: andersschuller, 2013-08-27 19:06:55
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();
    }
}

Ce code est cassé. Vous essayez d'ajouter à cart index itemCount. Cela jettera l'index hors des exécutions liées. bref si vous augmentez la taille de votre panier à la fin.

Cela provoque également beaucoup d'endroits vides dans votre tableau. Vous n'ajoutez pas votre prochain Article à la prochaine place de votre arra mais vous sautez quantité places à venir. Cela provoque certaines des valeurs de votre tableau null. Ceci est le plus susceptible de provoquer le NullPointerExceütion dans toString().

Pour savoir comment implémenter cette liste auto-croissante. Vous voudrez peut-être jeter un oeil à la classe ArrayList qui vient avec le JDK.

Il y a d'autres points que je veux souligner:

  • google javaDoc et l'utiliser à la place de vos propres commentaires
  • remplacer votre pour la boucle dans toString() avec pour chaque boucle
 1
Author: Tobias Kremer, 2013-08-27 19:09:33

Le problème réside à la fois dans votre méthode addToCart. Si vous tapez ce code:

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

Le panier aura les attributs suivants:

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

Le problème est que addToCart ne modifie que l'élément "itemcount" du tableau cart sans tenir compte du nombre d'éléments ajoutés. De plus, cart[0] restera à null pour toujours. Vous devriez remplacer ces lignes itemCount + = quantité; panier[itemCount] = temp;

Par

for ( int i =0 ; i<quantity;i++)
{
     cart[itemCount+i] = temp;
} 
itemCount += quantity;
 0
Author: Julien, 2013-08-27 18:58:12