实体类goods
柜台类Counter
package cn.zuoy.test; import cn.zuoy.test.Goods; import javax.management.Descriptor; import java.security.Key; import java.util.Scanner; /* * 增加菜单,目的:通过菜单选择执行功能 * */ public class Counter { //柜台商品列表,固定10个商品位置 private Goods[] goods = new Goods[10]; private int num; //柜台商品数量 //无参构造器初始化2个商品 public Counter(){ this.goods[0]=new Goods(1001,"巧克力",25,"美味可口,恋爱必备!"); this.goods[1]=new Goods(1002,"卫龙辣条",1,"隔壁小孩馋哭了!"); num = 2;//柜台有两个商品 } //展示商品 public void show(){ System.out.println("---------柜台商品信息---------"); // 展示柜台所有的商品(不能输出null) for (int i = 0; i < goods.length; i++) { if(goods[i]!=null) { System.out.println(goods[i]); } } System.out.println("此时柜台有"+num+"个商品"); } //增加上架商品功能 public void add(){ // System.out.println("请输入商品编号"); Goods good = new Goods(); // Scanner sc = new Scanner(System.in); // int id = sc.nextInt(); // good.setId(id); // id(); System.out.println("请输入商品名称"); String name = new Scanner(System.in).nextLine(); good.setName(name); System.out.println("请输入商品价格"); double price = new Scanner(System.in).nextDouble(); good.setPrice(price); System.out.println("请输入商品特点"); String desc = new Scanner(System.in).nextLine(); good.setDesc(desc); for(int i = 0; i < goods.length; i++){ if(goods[i] == null){ goods[i] =new Goods(1001+i, name, price, desc); num++; System.out.println("添加结束"); break; } } } // 增加下架商品功能 public void delete(){ System.out.println("请输入要下架商品的序号:"); Scanner sc = new Scanner(System.in); int id = sc.nextInt(); for (int i = 0; i < goods.length; i++) { if(goods[i]!=null && goods[i].getId() == id){ goods[i] =null; num--; System.out.println("下架成功"); } } } // 增加调整价格功能 public void update(){ System.out.println("请输入要修改商品的序号:"); Scanner sc = new Scanner(System.in); int id = sc.nextInt(); for (int i = 0; i < goods.length; i++) { if (goods[i]!=null && goods[i].getId() == id) { System.out.println("请输入要修改商品的价格:"); Scanner s = new Scanner(System.in); double price = s.nextDouble(); goods[i].setPrice(price); System.out.println("修改成功"); break; } } } } 测试类
package cn.zuoy.test; import java.util.Scanner; public class CounterTest { public static void main(String[] args) { Counter cou = new Counter(); while (true){ System.out.println("----------"); System.out.println("---1,商品列表 2.商品上架---"); System.out.println("---3.下架商品 4.调整价格---"); System.out.println("---0.退出 ---"); int key = new Scanner(System.in).nextInt(); //调用counter方法类进行对应操作 switch (key){ case 1:cou.show();break;//全查 case 2:cou.add();break;//添加商品 case 3:cou.delete();break;//删除商品 case 4:cou.update();break;//修改商品价格 case 0:System.exit(0);//退出 default: System.out.println("输入错误,请重新输入"); break; } } } }