題目需求
- 雞蛋庫存 100 顆
- 單價:1 元/顆,10 顆以上 0.8 元/顆 (批發價)
- 輸入購買數量,輸出應付金額與剩餘庫存

完整實作代碼
import java.util.Scanner;
public class EggSales {
public static void main(String[] args) {
final int INITIAL_STOCK = 100;
final double RETAIL_PRICE = 1.0;
final double WHOLESALE_PRICE = 0.8;
final int WHOLESALE_THRESHOLD = 10;
int stock = INITIAL_STOCK;
Scanner scanner = new Scanner(System.in);
System.out.println("=== 雞蛋銷售系統 ===");
System.out.printf("當前庫存: %d 顆%n", stock);
System.out.printf("零售價: %.1f 元/顆, 批發價(≥%d顆): %.1f 元/顆%n",
RETAIL_PRICE, WHOLESALE_THRESHOLD, WHOLESALE_PRICE);
while (true) {
System.out.print("\n請輸入購買數量 (0 結束): ");
if (!scanner.hasNextInt()) {
System.out.println("輸入無效,請輸入整數");
scanner.next(); // 清除無效輸入
continue;
}
int quantity = scanner.nextInt();
if (quantity == 0) break;
if (quantity < 0) {
System.out.println("數量不能為負數");
continue;
}
if (quantity > stock) {
System.out.printf("庫存不足,僅剩 %d 顆%n", stock);
continue;
}
double unitPrice = (quantity >= WHOLESALE_THRESHOLD) ? WHOLESALE_PRICE : RETAIL_PRICE;
double total = quantity * unitPrice;
stock -= quantity;
System.out.printf("單價: %.1f 元%n", unitPrice);
System.out.printf("應付金額: %.2f 元%n", total);
System.out.printf("剩餘庫存: %d 顆%n", stock);
}
System.out.println("感謝使用,再見!");
scanner.close();
}
}
關鍵邏輯解析
| 條件 | 單價 | 計算公式 |
| quantity < 10 | 1.0 | quantity × 1.0 |
| quantity ≥ 10 | 0.8 | quantity × 0.8 |
進階擴展建議
- 多商品支援:
Map<String, Product> 管理不同商品
- 交易記錄:
List<Transaction> 記錄每筆銷售
- 庫存預警:低於閾值時提醒進貨
- 持久化:檔案/資料庫儲存庫存與交易
- GUI 介面:Swing/JavaFX 建立視窗版本
常見錯誤避坑
- ❌
int total = quantity * 0.8 → 整數截斷誤差
- ✅
double total = quantity * 0.8 → 浮點數運算
- ❌ 未檢查庫存直接扣減
- ✅ 先驗證
quantity <= stock
- ❌
Scanner 未關閉 → 資源洩漏
- ✅
try-with-resources 或 finally 關閉