//定義商品類,包含名稱,貨號,單價,數量計價單位,金額 public class GoodsItem{ private String name; private String id; private int number; private String unit; private double money; //構造方法 public GoodsItem(){} GoodItem(String name,String id,double price ,int number,String unit,double money){ this.name = name ; this.id= id; this.price = price; this.number = number; this.money = money; } //get/set 方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } } //實現主幹邏輯,main方法. import java.util.ArrayList; import java.util.Scanner; public class ShoppingReceipt { static ArrayList<GoodItem>data = new ArrayList<GoodItem>(); public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("歡迎使用超市管理系統"); initData(); } private static void initData() { // TODO Auto-generated method stub GoodItem sls = new GoodItem("少林寺核桃","090115",15.5,0,"個",0); GoodItem shk = new GoodItem("尚康餅乾", "090027", 14.5, 0, "個", 0); data.add(sls); data.add(shk); while(true){ System.out.println("請輸入你要進行的操做:1 輸入購買數量 2 打印小票 3 退出"); Scanner sc = new Scanner(System.in); int optNumber = sc.nextInt(); switch(optNumber){ case 1: enterNumber(); break; case 2: printReceipt(); case 3: System.out.println("歡迎下次光臨"); System.exit(0); default: System.out.println("請輸入正確的數字!"); break; } } } private static void printReceipt() { // TODO Auto-generated method stub System.out.println("歡迎光臨"); System.out.println("品名 售價 數量 單位 金額"); System.out.println("-------------------"); int totalNumber =0; double totalMoney =0; for (int i = 0; i < data.size(); i++) { //依次獲取每個商品項 GoodItem g = data.get(i); //打印商品項 System.out.println(""+g.getName()+g.getId()+" "+g.getPrice()+" "+g.getNumber()+" + "+g.getMoney()); //累加數量與金額 totalNumber += g.getNumber(); totalMoney += g.getMoney(); } System.out.println("-------------------------------------------"); //票腳 System.out.println("共"+data.size()+"項商品"); System.out.println("共"+totalNumber+"件商品"); System.out.println("共"+totalMoney+"元"); System.out.println(); } private static void enterNumber() { // TODO Auto-generated method stub for(int i =0;i<data.size();i++){ GoodItem thisGoods = data.get(i); String thisGoodsName = thisGoods.getName(); System.out.println("請輸入"+thisGoodsName+"的購買數量"); Scanner sc = new Scanner(System.in); int thisGoodsNumber =sc.nextInt(); double thisGoodsMoney = thisGoods.getPrice()*thisGoodsNumber; thisGoods.setNumber(thisGoodsNumber); thisGoods.setMoney(thisGoodsMoney); } } }