Java NetBeans电商应用:从订单字符串提取金额与数量计算总价
解析订单字符串计算总价解决方案
方案1:直接解析现有订单字符串
如果不想改动现有添加订单的逻辑,可通过字符串解析提取价格和数量,步骤如下:
- 将文本区域内容按行拆分,逐行处理
- 用
indexOf("£")定位价格起始位置,再通过分割符x拆分价格和数量 - 处理格式异常(如空行、格式错误的行),避免程序崩溃
代码示例:
// 获取文本区域的所有订单内容 String orderContent = OrderSummary_txt.getText(); // 按换行符拆分每一条订单 String[] orderLines = orderContent.split("\n"); double totalAmount = 0.0; for (String line : orderLines) { // 跳过空行 if (line.trim().isEmpty()) continue; // 找到英镑符号的位置 int poundPos = line.indexOf("£"); if (poundPos == -1) continue; // 跳过无效订单行 // 截取英镑符号后的部分,再按"x"拆分价格和数量 String priceQtyStr = line.substring(poundPos + 1).trim(); String[] parts = priceQtyStr.split("\\s*x\\s*"); // 匹配x前后的任意空格 if (parts.length != 2) continue; // 格式不对的行直接跳过 try { // 解析价格和数量,去掉数量末尾可能的点号 double price = Double.parseDouble(parts[0]); int quantity = Integer.parseInt(parts[1].replace(".", "").trim()); // 累加金额 totalAmount += price * quantity; } catch (NumberFormatException e) { // 解析失败时跳过该行,也可添加提示 continue; } } // 把总价格式化后显示到标签 totalLabel.setText(String.format("订单总价: £%.2f", totalAmount));
方案2:面向对象重构(更健壮)
字符串解析易受格式变化影响(如商品名含"x"或"£"),更靠谱的方式是用对象存储商品信息,避免后续解析麻烦:
- 定义商品类,封装名称和价格:
class Product { private String name; private double price; public Product(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public double getPrice() { return price; } // 重写toString,让组合框显示带价格的文本 @Override public String toString() { return name + " £" + String.format("%.2f", price); } }
- 初始化商品组合框时,直接添加
Product对象:
// 示例:添加商品到组合框 Items_cmbo.addItem(new Product("Apples", 1.25)); Items_cmbo.addItem(new Product("Bananas", 0.75));
- 维护订单列表,添加订单时直接记录商品和数量:
// 全局或类内定义订单列表 List<OrderItem> orderList = new ArrayList<>(); // 添加订单的按钮事件里: Product selectedProduct = (Product) Items_cmbo.getSelectedItem(); int quantity = Integer.parseInt((String) Quantity_cmbo.getSelectedItem()); // 添加到文本区域 OrderSummary_txt.append(selectedProduct.toString() + " x " + quantity + "\n"); // 添加到订单列表 orderList.add(new OrderItem(selectedProduct, quantity)); // 计算总价 double total = 0.0; for (OrderItem item : orderList) { total += item.getProduct().getPrice() * item.getQuantity(); } totalLabel.setText(String.format("订单总价: £%.2f", total)); // 定义订单项类 class OrderItem { private Product product; private int quantity; public OrderItem(Product product, int quantity) { this.product = product; this.quantity = quantity; } public Product getProduct() { return product; } public int getQuantity() { return quantity; } }
两种方案对比:
- 方案1适合快速修改现有代码,无需调整结构,但容错性差
- 方案2更健壮,后续扩展功能(如修改订单、保存订单)更方便,推荐使用
内容的提问来源于stack exchange,提问作者Chris Butler
相关产品推荐
相关产品推荐

