源代码:
public class 购物车案例 {
public static void main(String[] args) {
Goods[] shopcar = new Goods[100];
while (true) {
System.out.println("请您选择如下命令进行操作:");
System.out.println("添加商品到购物车: add");
System.out.println("查询商品到购物车: find");
System.out.println("修改商品购买数量: update");
System.out.println("结算商品购买金额: pay");
Scanner sc = new Scanner(System.in);
System.out.println("请您输入命令:");
String command = sc.next();
switch (command) {
case "add":
add(shopcar);
break;
case "find":
find(shopcar);
break;
case "update":
update(shopcar);
break;
case "pay":
pay(shopcar);
break;
default:
System.out.println("您输入的命令有误!!");
}
}
}
private static void pay(Goods[] shopcar) {
find(shopcar);
double money = 0;
for (int i = 0; i < shopcar.length; i++) {
Goods g = shopcar[i];
if (g != null) {
money += (g.price * g.many);
} else {
break;
}
}
System.out.println("一共消费" + money + "元");
}
private static void update(Goods[] shopcar) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要修改商品信息的id");
int id = sc.nextInt();
Goods g = chaxun(shopcar, id);
if (g == null) {
System.out.println("对不起,没有查询到该id的商品");
} else {
System.out.println("请您输入" + g.name + "商品的最新购买数量");
int many = sc.nextInt();
g.many = many;
System.out.println("修改完成");
find(shopcar);
}
}
private static Goods chaxun(Goods[] shopcar, int id) {
for (int i = 0; i < shopcar.length; i++) {
if (shopcar[i] != null) {
if (shopcar[i].id == id) {
return shopcar[i];
}
} else {
break;//找完了前面存在的商品 没找到一样id的
}
}
return null;//找完了所有100个商品 没有找到一样id的
}
private static void find(Goods[] shopcar) {
System.out.println("------------查询购物车信息如下-------------");
System.out.println("编号tt名称tt价格tt数量");
for (int i = 0; i < shopcar.length; i++) {
if (shopcar[i] != null) {
System.out.println(shopcar[i].id + "tt" + shopcar[i].name + "tt" + shopcar[i].price + "tt" + shopcar[i].many);
} else {
break;
}
}
}
private static void add(Goods[] shopcar) {
Scanner sc = new Scanner(System.in);//录入用户购买商品的信息
System.out.println("请您输入购买商品的编号");
int id = sc.nextInt();
System.out.println("请您输入购买商品的名称");
String name = sc.next();
System.out.println("请您输入购买商品的数量");
int many = sc.nextInt();
System.out.println("请您输入购买商品的价格");
double price = sc.nextDouble();
Goods g = new Goods();//将该信息封装成一个商品对象
g.id = id;
g.name = name;
g.many = many;
g.price = price;
//把这个商品对象存入购物车数组
for (int i = 0; i < shopcar.length; i++) {
if (shopcar[i] == null) {
shopcar[i] = g;
break;
}
}
System.out.println("您的商品" + g.name + "已经存入购物车中");
}
}
--------------------------------------------------------------------------------------------------------------------------------
运行结果(程序测试)



