为什么 Java 函数在添加到购物车时会使数量相乘?

huangapple go评论72阅读模式
英文:

Why does Java function multiply the quantity when adding to cart?

问题

我正在尝试将新产品添加到购物车。当我添加第一个产品时,它会被正确添加。当产品已存在时,它会正确递增,但是当购物车中已经存在产品并尝试添加新产品时,数量会增加1个。

protected void addToCart(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    int productId = Integer.parseInt(request.getParameter("productId"));
    if (session.getAttribute("cart") == null) {
        ArrayList<Item> item = new ArrayList<>();
        item.add(new Item(ProductModel.getProduct(productId), 1));
        session.setAttribute("cart", item);
    } else {
        ArrayList<Item> item = (ArrayList<Item>) session.getAttribute("cart");
        boolean productExists = false;
        for (int i = 0; i < item.size(); i++) {
            // This line increments the quantity of the existing product correctly
            if (item.get(i).getProduct().getId() == productId) {
                item.get(i).setQuantity(item.get(i).getQuantity() + 1);
                productExists = true;
                break;  // Exit the loop since product is found
            }
        }
        if (!productExists) {
            // Here, add the new product to the cart with quantity 1
            item.add(new Item(ProductModel.getProduct(productId), 1));
        }
        session.setAttribute("cart", item);
    }
}

可能的问题是,您在遍历现有购物车项目时,对于每个项目都尝试将新产品添加到购物车。为了解决这个问题,我在代码中添加了一个布尔变量productExists来跟踪是否已经存在该产品,并相应地调整了代码逻辑。如果产品已存在,我在其数量上进行递增。如果不存在,我才将新产品添加到购物车。这样可以避免重复添加相同的产品。

英文:

I am trying to add a new product into cart. When I add the first product, it's added correctly. When the product already exist, it increment correctly but when there are products existing into cart and try to add a new product it adds 1 more in quantity.

protected void addToCart(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    int productId = Integer.parseInt(request.getParameter(&quot;productId&quot;));
    if (session.getAttribute(&quot;cart&quot;) == null) {
        ArrayList&lt;Item&gt; item = new ArrayList&lt;&gt;();
        item.add(new Item(ProductModel.getProduct(productId), 1));
        session.setAttribute(&quot;cart&quot;, item);
    } else {
        ArrayList&lt;Item&gt; item = (ArrayList&lt;Item&gt;) session.getAttribute(&quot;cart&quot;);
        for (int i = 0; i &lt; item.size(); i++) {
            // This line increment the product correctly
            if (item.get(i).getProduct().getId() == productId) {
                item.get(i).setQuantity(item.get(i).getQuantity() + 1);
            } else {
                // Here the product is added twice instead of once
                item.add(new Item(ProductModel.getProduct(productId), 1));
            }
            session.setAttribute(&quot;cart&quot;, item);
        }
        
    }
}

What would be the problem?

答案1

得分: 1

问题是,当找到一个没有相同产品ID的项目时,代码会向购物车中添加新项目。它应该这样做:只有当没有项目具有相同的产品ID时,才添加新项目。

您可以使用一个布尔变量来跟踪是否找到具有匹配产品ID的项目,如果在循环中没有找到,则在循环中添加新项目。

boolean foundExistingProduct = false;
ArrayList<Item> item = (ArrayList<Item>) session.getAttribute("cart");
for (int i = 0; i < item.size(); i++) {
    if (item.get(i).getProduct().getId() == productId) {
        item.get(i).setQuantity(item.get(i).getQuantity() + 1);
        session.setAttribute("success", "已将现有产品添加到购物车!");
        request.getRequestDispatcher("Products").forward(request, response);
        foundExistingProduct = true;
        break;
    }
}

if (!foundExistingProduct) {
    item.add(new Item(ProductModel.getProduct(productId), 1));
    session.setAttribute("success", "已将另一产品添加到购物车!");
    request.getRequestDispatcher("Products").forward(request, response);
}

session.setAttribute("cart", item);
英文:

The problem is that the code adds a new item to the cart when you find an item that doesn't have the same product ID. What it should be doing is add a new item if no item has the same product ID.

You can use a boolean variable to keep track of whether you found an item with a matching product ID or not, and add a new item in the loop if you did not.

boolean foundExistingProduct = false;
ArrayList&lt;Item&gt; item = (ArrayList&lt;Item&gt;) session.getAttribute(&quot;cart&quot;);
for (int i = 0; i &lt; item.size(); i++) {
    if (item.get(i).getProduct().getId() == productId) {
        item.get(i).setQuantity(item.get(i).getQuantity() + 1);
        session.setAttribute(&quot;success&quot;, &quot;An existing product is added to shopping cart!&quot;);
        request.getRequestDispatcher(&quot;Products&quot;).forward(request, response);
        foundExistingProduct = true;
        break;
    }
}

if (!foundExistingProduct) {
    item.add(new Item(ProductModel.getProduct(productId), 1));
    session.setAttribute(&quot;success&quot;, &quot;Another product is added to shopping cart!&quot;);
    request.getRequestDispatcher(&quot;Products&quot;).forward(request, response);
}

session.setAttribute(&quot;cart&quot;, item);

huangapple
  • 本文由 发表于 2020年8月28日 19:06:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63632591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定