編寫收銀台程序,輸入商品單價、數量、實收金額,輸出應收金額與找零。進階需求支援多商品輸入、階梯折扣。
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 結束錄入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 |
| 擴展性 | 難 | 策略模式可替換折扣算法 |
BigDecimal**,避免浮點誤差。DiscountStrategy 介面,支援滿減、會員價、限時促銷等複雜規則。