用以前學過的知識,可以簡單地做一個超市庫存管理系統: 定義一個商品類: 然後: ...
用以前學過的知識,可以簡單地做一個超市庫存管理系統:
定義一個商品類:
public class FruitItem { int ID; String name; double price; int number; double money; }
然後:
import java.util.ArrayList; import java.util.Scanner; public class Shop { public static void main(String[] args) { ArrayList<FruitItem> array = new ArrayList<FruitItem>(); init(array); while (true) { mainMenu(); int choose = chooseFunction(); switch (choose) { case 1: showFruitList(array); break; case 2: addFruit(array); break; case 3: deleteFruit(array); break; case 4: updateFruit(array); break; case 5: return; default: System.out.println("輸入的序號不存在"); break; } } } public static void updateFruit(ArrayList<FruitItem> array){ System.out.println("您選擇的是修改功能"); System.out.println("請輸入商品編號:"); Scanner sc = new Scanner(System.in); int ID = sc.nextInt(); for (int i = 0; i < array.size(); i++) { FruitItem item =array.get(i); if(item.ID==ID){ System.out.println("請輸入新的商品編號:"); item.ID = sc.nextInt(); System.out.println("請輸入新的商品名稱:"); item.name = sc.next(); System.out.println("請輸入新的商品價格:"); item.price = sc.nextDouble(); System.out.println("商品修改成功"); return; } } System.out.println("您輸入的編號不存在"); } public static void deleteFruit(ArrayList<FruitItem> array){ System.out.println("您選擇的是刪除功能"); System.out.println("請輸入商品的編號:"); Scanner sc = new Scanner(System.in); int ID = sc.nextInt(); for (int i = 0; i < array.size(); i++) { FruitItem item = array.get(i); if(item.ID == ID){ array.remove(i); System.out.println("刪除成功"); return; } } System.out.println("您輸入的編號不存在"); } public static void addFruit(ArrayList<FruitItem> array) { System.out.println("您選擇的是添加商品功能"); Scanner sc = new Scanner(System.in); System.out.println("請輸入商品的編號:"); int ID = sc.nextInt(); System.out.println("請輸入商品的名字:"); String name = sc.next(); System.out.println("請輸入商品的單價:"); double price = sc.nextDouble(); FruitItem item = new FruitItem(); item.ID = ID; item.name = name; item.price = price; array.add(item); } public static void showFruitList(ArrayList<FruitItem> array) { System.out.println(); System.out.println("==========商品庫存清單=========="); System.out.println("商品編號 商品名稱 商品單價"); for (int i = 0; i < array.size(); i++) { FruitItem item = array.get(i); System.out.println(item.ID + " " + item.name + " " + item.price); } } public static void init(ArrayList<FruitItem> array) { FruitItem f1 = new FruitItem(); f1.ID = 9527; f1.name = "香蕉"; f1.price = 3.0; FruitItem f2 = new FruitItem(); f2.ID = 9008; f2.name = "蘋果"; f2.price = 5.6; FruitItem f3 = new FruitItem(); f3.ID = 9879; f3.name = "橘子"; f3.price = 6.6; array.add(f1); array.add(f2); array.add(f3); } public static void mainMenu() { System.out.println(); System.out.println("==========歡迎光臨某某超市=========="); System.out.println("1:貨物清單 2:添加貨物 3:刪除貨物 4:修改貨物 5:退出"); System.out.println("請您輸入要操作的功能序號"); } public static int chooseFunction() { Scanner sc = new Scanner(System.in); return sc.nextInt(); } }