首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 控制台收銀程序:從基礎版到折扣優化版完整演進

     編輯:Java 綜合教學

需求背景

編寫收銀台程序,輸入商品單價、數量、實收金額,輸出應收金額與找零。進階需求支援多商品輸入、階梯折扣。

版本一:單商品基礎版

import java.util.Scanner;

public class CashierV1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("請輸入商品數量:");
        int qty = sc.nextInt();

        System.out.print("請輸入商品單價:");
        float price = sc.nextFloat();

        System.out.print("請輸入實收金額:");
        float paid = sc.nextFloat();

        float total = price * qty;
        float change = paid - total;

        System.out.printf("應收金額:%.2f 元%n", total);
        System.out.printf("找零金額:%.2f 元%n", change);
    }
}

版本二:多商品 + 階梯折扣優化版

業務規則

  • 輸入 end 結束錄入
  • 每行輸入:商品名、單價、數量
  • 折扣檔位:
      • < 100 元:無折扣
      • 100~199.99:8 折
      • 200~299.99:7 折
      • ≥ 300:6 折

完整代碼

import java.util.*;

public class CashierV2 {
    static class Item {
        String name;
        double price;
        int qty;
        Item(String n, double p, int q) { name = n; price = p; qty = q; }
        double subTotal() { return price * qty; }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<Item> cart = new ArrayList<>();

        System.out.println("=== 收銀系統 v2.0 ===");
        System.out.println("格式:商品名 單價 數量(輸入 end 結束)");

        while (true) {
            System.out.print("> ");
            String line = sc.nextLine().trim();
            if ("end".equalsIgnoreCase(line)) break;

            String[] parts = line.split("\\s+");
            if (parts.length != 3) {
                System.out.println("輸入格式錯誤,請重新輸入");
                continue;
            }
            try {
                String name = parts[0];
                double price = Double.parseDouble(parts[1]);
                int qty = Integer.parseInt(parts[2]);
                if (price < 0 || qty <= 0) throw new NumberFormatException();
                cart.add(new Item(name, price, qty));
                System.out.printf("已加入:%s × %d = %.2f 元%n", name, qty, price * qty);
            } catch (NumberFormatException e) {
                System.out.println("單價/數量必須為正數");
            }
        }

        // 計算原價總額
        double rawTotal = cart.stream().mapToDouble(Item::subTotal).sum();

        // 計算折扣
        double discountRate;
        if (rawTotal >= 300) discountRate = 0.6;
        else if (rawTotal >= 200) discountRate = 0.7;
        else if (rawTotal >= 100) discountRate = 0.8;
        else discountRate = 1.0;

        double finalTotal = rawTotal * discountRate;

        System.out.println("\n=== 結算單 ===");
        cart.forEach(i -> System.out.printf("%s\t%.2f × %d = %.2f%n", i.name, i.price, i.qty, i.subTotal()));
        System.out.printf("原價小計:%.2f 元%n", rawTotal);
        System.out.printf("折扣比例:%.0f 折%n", discountRate * 10);
        System.out.printf("應收金額:%.2f 元%n", finalTotal);

        // 收款與找零
        double paid = 0;
        while (paid < finalTotal) {
            System.out.print("請輸入實收金額:");
            try {
                paid = Double.parseDouble(sc.nextLine().trim());
                if (paid < finalTotal) System.out.println("金額不足,請補齊");
            } catch (NumberFormatException e) {
                System.out.println("請輸入有效數字");
            }
        }
        System.out.printf("找零金額:%.2f 元%n", paid - finalTotal);
        System.out.println("交易完成,歡迎再次光臨!");
    }
}

關鍵優化點

維度V1 基礎版V2 優化版
商品數量單一動態列表
折扣策略固定 8 折階梯折扣,業務可配置
輸入健壯性無校驗格式/範圍校驗、異常捕獲
金額精度float 易丟失精度double / 建議生產用 BigDecimal
擴展性難策略模式可替換折扣算法

生產級建議

  1. 金額計算**務必使用 BigDecimal**,避免浮點誤差。
  2. 折扣策略抽象為 DiscountStrategy 介面,支援滿減、會員價、限時促銷等複雜規則。
  3. 引入訂單號、操作員、支付方式(現金/微信/支付寶/刷卡)、小票打印等完整業務閉環。
  4. 單元測試覆蓋邊界值:0 元、99.99、100、199.99、200、299.99、300。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved