/*
管理者能夠進行的操作有3項(檢視、修改、退出),
我們可以采用(switch)菜單的方式來完成。
-------------庫存管理------------
1.檢視庫存清單
2.修改商品庫存數量
3.退出
請輸入要執行的操作序号:
每一項功能操作,我們采用方法進行封裝,這樣,可使程式的可讀性增強。
選擇1.檢視庫存清單”功能,則控制台列印庫存清單
選擇2.修改商品庫存數量”功能,則對每種商品庫存數進行更新
選擇3.退出”功能,則退出庫存管理,程式結束
使用集合來存取商品資訊
*/
import java.util.ArrayList;
import java.util.Scanner;
public class Shop{
public static void main(String[] args){
//定義集合,存儲的是Laptop類型變量
ArrayList<Laptop> array = new ArrayList<Laptop>();
add(array);
while(true){
int choose = chooseFunction();
switch(choose){
//檢視庫存清單
case 1:
printArrayList(array);
break;
case 2:
changeCount(array);
break;
case 3:
return;
default:
System.out.println("Sorry,暫時不提供此功能");
break;
}
}
}
/*
修改商品庫存數量
*/
public static void changeCount(ArrayList<Laptop> array){
for(int i = 0;i < array.size(); i++){
Laptop b = array.get(i);
Scanner s = new Scanner(System.in);
System.out.print("要修改商品"+b.brand+"的庫存是:");
b.count = s.nextInt();
}
}
/*
檢視庫存清單”功能,則控制台列印庫存清單
*/
public static void printArrayList( ArrayList<Laptop> array){
int totalCount = 0;
double totalMoney = 0;
for(int i = 0;i < array.size() ; i++){
//存儲集合的時候,集合add(b1) b1 是Name類型變量
//擷取的時候,集合get方法,擷取出來的是什麼
Laptop b = array.get(i);
System.out.println(b.brand+" "+b.size+" "+b.price+" "+b.count);
totalCount += b.count;
totalMoney += b.price*b.count;
}
System.out.println("庫存總數:"+totalCount);
System.out.println("庫存商品總金額:"+totalMoney);
}
/*
定義方法,實作向集合中添加品牌,
*/
public static void add(ArrayList<Laptop> array){
Laptop b1 = new Laptop();
Laptop b2 = new Laptop();
Laptop b3 = new Laptop();
b1.brand = "MacBookAir";
b1.size = 13.3 ;
b1.price = 6988.88;
b1.count = 5;
b2.brand = "Thinkpad T450";
b2.size = 14.0 ;
b2.price = 5999.99;
b2.count = 10;
b3.brand = "Asus-FL5800";
b3.size = 15.6 ;
b3.price = 4999.5;
b3.count = 18;
//将laptop變量存到集合中
array.add(b1);
array.add(b2);
array.add(b3);
}
/*
庫存管理界面
@return傳回使用者選擇的功能
*/
public static int chooseFunction(){
System.out.println("-------------庫存管理------------");
System.out.println("1.檢視庫存清單");
System.out.println("2.修改商品庫存數量");
System.out.println("3.退出");
System.out.println("請選擇您要使用的功能:");
Scanner ran = new Scanner(System.in);
int number = ran.nextInt();
return number;
}
}
要注意加上 import 引用的類 可以避免編譯找不到符号的錯誤
定義一個名為Laptop的類
/*
建立一個類:電腦
包含的屬性:品牌 尺寸 價格 庫存數
*/
public class Laptop{
String brand;//品牌
double size;//尺寸
double price;//價格
int count;//庫存數
}
得到的結果是:
