package Demo; import java.util.Scanner; public class ShopCarTest { public static void main(String[] args) { Goods[] shopCar = new Goods[100]; while (true) { System.out.println("请你选择如下命令进行操作:"); System.out.println("添加商品到购物车:add"); System.out.println("查询商品到购物车:query"); System.out.println("修改商品的购买数量:update"); System.out.println("结算商品得购金额:pay"); Scanner sc = new Scanner(System.in); System.out.println("请输入命令:"); String commend = sc.next(); switch (commend) { case "add": addGoods(shopCar ,sc); break; case "query": queryGoods(shopCar); break; case "update": updateGoods(shopCar,sc); break; case "pay": payGoods(shopCar); break; default: System.out.println("没有该功能!"); } } } private static void payGoods(Goods[] shopCar) { queryGoods(shopCar); //1、定义一个求和变量累加金额 double money = 0; //2、遍历购物车数组中的全部商品对象,累加单价*数量 //[g1,g2,null,...] for (int i = 0; i < shopCar.length; i++) { Goods g = shopCar[i]; if(g != null){ money += (g.price * g.buyNumber); } else{ break; } } System.out.println("订单总金额" + money); } private static void updateGoods(Goods[] shopCar ,Scanner sc) { //让用户输入要修改的商品id,根据id查出要修改的商品对象 while (true) { System.out.println("请你输入要求修改的商品id:"); int id = sc.nextInt(); Goods g = getGoodsById(shopCar,id); if(g == null){ //没有该商品 System.out.println("对不起,没有购买商品"); } else { //说明存在该商品对象,可以修改它了 System.out.println("请你输入:" + g.name + "商品最新购买数量:"); int buyNumber = sc.nextInt(); g.buyNumber = buyNumber; System.out.println("修改完成!"); queryGoods(shopCar); break; } } } public static Goods getGoodsById(Goods[] shopCar ,int id){ //shopCar = [g1,g2,g3,null.null,...] for (int i = 0; i < shopCar.length; i++) { Goods g = shopCar[i]; if(g != null){ //判断这个商品的id是否是我们要找的 if(g.id == id){ return g; } }else{ return null; } } //找完所有商品,都没有找打 return null; } /** 查询购物车中的商品对象信息,并展示出来 */ private static void queryGoods(Goods[] shopCar) { System.out.println("===========查询购物车信息如下==========="); System.out.println("编号\t\t名称\t\t\t价格\t\t\t购买数量"); //shopCar = [g1,g2,g3,null,null,.....] for (int i = 0; i < shopCar.length; i++) { Goods g = shopCar[i]; if(g !=null){ //展示这个商品对象 System.out.println(g.id + "\t\t" + g.name +"\t\t\t" + g.price + "\t\t\t"+ g.buyNumber); } else{ //遍历结果 break; } } } private static void addGoods(Goods[] shopCar, Scanner sc) { //1、录入用户输入的购买商品的信息 System.out.println("请输入购买商品的编号(不重复):"); int id = sc.nextInt(); System.out.println("请输入购买商品的名称:"); String name = sc.next(); System.out.println("请输入购买商品的数量:"); int buyNumber = sc.nextInt(); System.out.println("请输入购买商品的价格:"); double price = sc.nextDouble(); //把这个购买商品的信息封装成一个商品对象 Goods g = new Goods(); g.id = id; g.name = name; g.buyNumber = buyNumber; g.price = price; //3、把在这个商品对象添加到购物车数组中去 // shopCar = [null,null,null,null.......] for (int i = 0;i < shopCar.length;i++){ if(shopCar[i] == null){ //说明此位置没有元素存入,把我们新买的商品添加到此处即可 shopCar[i] = g; break; // 结束,因为商品已经成功存入了,不需要继续找位置了 } } System.out.println("你的商品:" + g.name +"添加到 购物车完成!"); } }
类
package Demo; public class Goods { int id; String name; double price; int buyNumber; }