要实现的功能如下
package supermarket;
import java.util.Scanner;
import java.util.ArrayList;
//貨物屬性類
class Goods{
int id;
String name;
double price;
}
//main方法
public class Supermarket {
public static void main(String[] args) {
ArrayList<Goods> list = new ArrayList<Goods>();
//添加貨物的方法
addGoods(list);
//登錄界面
while(true){
int number = register();
switch(number){
case 1: account(list);
break;
case 2: add(list);
break;
case 3: delete(list);
break;
case 4: update(list);
break;
case 5: return;
case 6: System.out.println("輸入錯誤!");
}
}
}
//登錄界面方法
public static int register(){
System.out.println("==============歡迎光臨itcast超市===============");
System.out.println("1.貨物清單");
System.out.println("2.添加新貨物");
System.out.println("3.刪除貨物");
System.out.println("4.修改貨物");
System.out.println("5.退出系統");
Scanner sc = new Scanner(System.in);
System.out.println("請輸入要操作的功能序號");
int choosenumber = sc.nextInt();
return choosenumber;
}
//講貨物存入集合中的方法
public static void addGoods(ArrayList<Goods> list){
Goods g1 = new Goods();
g1.id = 9001;
g1.name = "少林寺酥饼核桃";
g1.price=120.8;
Goods g2 = new Goods();
g2.id = 9002;
g2.name = "尚康杂粮牡丹饼";
g2.price=108.6;
Goods g3 = new Goods();
g3.id = 9003;
g3.name = "新疆原产哈密瓜";
g3.price=223.5;
list.add(g1);
list.add(g2);
list.add(g3);
}
//貨物清單
public static void account(ArrayList<Goods> list){
System.out.println("貨物編號 貨物名稱 貨物價格");
for(int i=0;i<list.size();i++){
Goods g0 = list.get(i);
System.out.println(g0.id+" "+g0.name+" "+g0.price);
}
}
//添加貨物方法
public static void add(ArrayList<Goods> list){
Scanner sc = new Scanner(System.in);
Goods g = new Goods();
System.out.println("請輸入商品的編號");
int a = sc.nextInt();
g.id = a;
System.out.println("請輸入商品的名稱");
String b = sc.next();
g.name = b;
System.out.println("請輸入商品的價格");
double c = sc.nextDouble();
g.price = c;
list.add(g);
}
//刪除貨物
public static void delete(ArrayList<Goods> list){
Scanner sc = new Scanner(System.in);
System.out.println("請輸入要刪除的貨物編號");
int nn = sc.nextInt();
for(int i=0;i<list.size();i++){
if(list.get(i).id==nn){
list.remove(i);
}
}
}
//修改貨物
public static void update(ArrayList<Goods> list){
Scanner sc = new Scanner(System.in);
System.out.println("請輸入要修改的貨物編號");
int num = sc.nextInt();
for(int i=0;i<list.size();i++){
if(num==list.get(i).id){
Goods g = new Goods();
System.out.println("請輸入新貨物的名字");
String s = sc.next();
list.get(i).name = s;
System.out.println("請輸入新貨物的價格");
double p = sc.nextDouble();
list.get(i).price=p;
}
}
}
}