You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java订单系统新增商品数量被覆盖的问题排查求助

文具订单系统购物车数量累加错误排查

我正在开发一个允许用户购买文具的订单系统,预期逻辑如下:

  • 先展示文具菜单,让用户输入商品ID和数量
  • 选中的商品加入购物车,若再次购买同商品则累加数量并显示小计

但现在遇到问题:添加购物车中没有的新商品时,新商品的数量会与之前商品的数量累加,不符合预期。修改过代码但问题依旧,希望有人指出代码错误。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import static java.nio.file.Files.size;
import java.util.Scanner;

public class Order {

    private int product_id;
    private String product_Name;
    private int orderQuantity = 0;
    private double price = 0.0;
    private double subTotal = 0;
    int size = 100;
    Product[] productList = new Product[size];
    int count = 0;
    Order[] orderList = new Order[size];

    public Order() {

    }

    public Order(int product_id, String product_Name, double price, int orderQuantity) {
        this.product_id = product_id;
        this.product_Name = product_Name;
        this.orderQuantity = orderQuantity;
    }

    public Order(int product_id, String product_Name, double price, double subTotal, int orderQuantity) {
        this.product_id = product_id;
        this.product_Name = product_Name;
        this.price = price;
        this.subTotal = subTotal;
        this.orderQuantity = orderQuantity;
    }

    public String getProduct_Name() {
        return product_Name;
    }

    public void setProduct_Name(String product_Name) {
        this.product_Name = product_Name;
    }

    public int getProduct_id() {
        return product_id;
    }

    public void setProduct_id(int product_id) {
        this.product_id = product_id;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getOrderQuantity() {
        return orderQuantity;
    }

    public void setOrderQuantity(int orderQuantity) {
        this.orderQuantity = orderQuantity;
    }

    public Order(double subTotal) {
        this.subTotal = subTotal;
    }

    public double getSubTotal() {
        return subTotal;
    }

    public void setSubTotal(double subTotal) {
        this.subTotal = subTotal;
    }

    public void Menu() {

        System.out.println("Stationaries");
        System.out.println("================");
        System.out.println("ID  Name                Price Quantity");
        System.out.println("=== =================== ===== ========");
        try {
            File product = new File("src/product.txt");
            Scanner order = new Scanner(product);

            while (order.hasNextLine()) {
                String[] data = order.nextLine().split("\\|");
                int product_id = Integer.parseInt(data[0]);
                String product_name = data[1];
                double product_price = Double.parseDouble(data[2]);
                int product_quantity = Integer.parseInt(data[3]);
                productList[count] = new Product(product_id, product_name, product_price, product_quantity);
                count++;
                System.out.printf("%-4d%-20s%-6.2f%-10d\n", product_id, product_name, product_price, product_quantity);
            }

            order.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }

    public void makeOrder() {
        char yesno;
        boolean check = false;
        int index = 0;
        int count1 = 0;
        int totalprice = 0;
        int finalQuantity = 0;
        boolean exist = false;
        double product_price;
        String product_Name;
        Scanner order = new Scanner(System.in);

        do {
            System.out.print("Enter product ID :");
            int product_Id = order.nextInt();
            product_Name = productList[product_Id - 1].getProduct_name();
            product_price = productList[product_Id - 1].getProduct_price();
            for (int i = 0; i < count; i++) {
                if (product_Id == productList[i].getProduct_id()) {
                    check = true;
                }
            }

            if (check) {
                System.out.print("Enter quantity : ");
                int quantity = order.nextInt();
                orderList[count1] = new Order(product_Id, product_Name, product_price, quantity);
                count1++;
            }

            for (int k = 0; k < count1; k++) {
                if (product_Id == orderList[k].getProduct_id()) {
                    index = k;
                    exist = true;
                    break;
                }
            }

            System.out.println("Shopping Cart");
            System.out.println("================");
            System.out.println("ID  Name                Price Quantity Subtotal");
            System.out.println("=== =================== ===== ======== ========");

            if (exist) {
                finalQuantity += orderList[index].getOrderQuantity();
                orderList[index].setOrderQuantity(finalQuantity);
                orderList[index].setSubTotal(orderList[index].getOrderQuantity() * product_price);
                System.out.printf("%-4d%-20s%-6.2f%-10d%-6.2f\n", orderList[index].getProduct_id(), orderList[index].getProduct_Name(), product_price, orderList[index].getOrderQuantity(), orderList[index].getSubTotal());
            } else {
                index++;
                orderList[index].setProduct_id(orderList[index].getProduct_id());
                orderList[index].setOrderQuantity(orderList[index].getOrderQuantity());
                orderList[index].setSubTotal(orderList[index].getOrderQuantity() * product_price);
                System.out.printf("%-4d%-20s%-6.2f%-10d%-6.2f\n", orderList[index].getProduct_id(), orderList[index].getProduct_Name(), product_price, orderList[index].getOrderQuantity(), orderList[index].getSubTotal());
            }
            System.out.print("Continue Order?(Y|N)");
            yesno = order.next().toUpperCase().charAt(0);
        } while (yesno == 'Y');
    }

}

核心错误点

  1. finalQuantity未循环重置:这个变量在方法开头定义,每次添加新商品时不会清零,导致新商品数量被错误累加之前的总数。
  2. 同商品重复添加到购物车数组:用户输入有效商品后,直接创建新Order对象存入orderList,未先检查购物车是否已有该商品,导致数组中出现多个同商品条目,后续判断逻辑混乱。
  3. check和exist未循环重置:这两个布尔变量在每次循环开始时未重置为false,会保留上一次的状态,导致逻辑判断出错。
  4. 新商品添加逻辑错误:else分支直接操作orderList[index],但此时index可能指向未初始化的数组位置,且未正确创建新商品的Order对象。

修复后的关键代码

public void makeOrder() {
    char yesno;
    Scanner order = new Scanner(System.in);

    do {
        boolean check = false; // 每次循环重置校验状态
        boolean exist = false; // 每次循环重置购物车存在标记
        int productIndex = -1;
        int quantity = 0;

        System.out.print("Enter product ID :");
        int product_Id = order.nextInt();

        // 校验商品ID是否存在
        for (int i = 0; i < count; i++) {
            if (product_Id == productList[i].getProduct_id()) {
                check = true;
                productIndex = i;
                break;
            }
        }

        if (check) {
            System.out.print("Enter quantity : ");
            quantity = order.nextInt();
            String product_Name = productList[productIndex].getProduct_name();
            double product_price = productList[productIndex].getProduct_price();

            // 检查购物车中是否已有该商品
            int cartIndex = -1;
            for (int k = 0; k < orderList.length; k++) {
                if (orderList[k] != null && product_Id == orderList[k].getProduct_id()) {
                    cartIndex = k;
                    exist = true;
                    break;
                }
            }

            if (exist) {
                // 累加已有商品数量
                int newQty = orderList[cartIndex].getOrderQuantity() + quantity;
                orderList[cartIndex].setOrderQuantity(newQty);
                orderList[cartIndex].setSubTotal(newQty * product_price);
            } else {
                // 添加新商品到购物车第一个空位置
                for (int k = 0; k < orderList.length; k++) {
                    if (orderList[k] == null) {
                        orderList[k] = new Order(product_Id, product_Name, product_price, quantity);
                        orderList[k].setSubTotal(quantity * product_price);
                        break;
                    }
                }
            }

            // 打印完整购物车
            System.out.println("Shopping Cart");
            System.out.println("================");
            System.out.println("ID  Name                Price Quantity Subtotal");
            System.out.println("=== =================== ===== ======== ========");
            for (Order item : orderList) {
                if (item != null) {
                    System.out.printf("%-4d%-20s%-6.2f%-10d%-6.2f\n",
                            item.getProduct_id(), item.getProduct_Name(),
                            item.getPrice(), item.getOrderQuantity(), item.getSubTotal());
                }
            }
        } else {
            System.out.println("无效的商品ID!");
        }

        System.out.print("继续下单?(Y|N)");
        yesno = order.next().toUpperCase().charAt(0);
    } while (yesno == 'Y');
}

额外优化建议

  • 用HashMap<Integer, Order>替代数组存储购物车,以商品ID为键,能直接定位商品,避免遍历数组,提升效率。
  • 拆分方法:将校验商品、处理购物车、打印购物车等逻辑拆分为独立方法,让代码更易读和维护。

内容的提问来源于stack exchange,提问作者LIM WENG NI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:15:37