//定义商品类
package shoppingcart;
public class Goods {
int id;//编号
String name;
double price;
int buyNum;
}
package shoppingcart;
import java.util.Scanner;
public class ShoppingCartTest {
public static void main(String[] args) {
Goods[] shopCar = new Goods[100];
while (true) {
System.out.println("请输入以下命令");
System.out.println("添加商品到购物车:add");
System.out.println("查询购物车商品展示:check");
/*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":
//添加商品
addGoods(shopCar);
break;
case "check":
//查询展示商品
checkGoods(shopCar);
break;
/*case "update":
//修改商品数量
updateGoods(shopCar);
break;
case "pay":
//结算
payGoods(shopCar);
break;*/
default:
System.out.println("您输入的命令有误");
}
}
}
/*private static void payGoods(Goods[] shopCar) {
double sum = 0.0;
Goods g = new Goods();
for (int i = 0; i < shopCar.length; i++) {
g = shopCar[i];
if (shopCar[i] != null) {
sum = sum + g.price * g.buyNum;
} else {
break;
}
}
System.out.println("您应该支付" + sum + "元");
}
private static void updateGoods(Goods[] shopCar) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入您要更改的商品种类数量");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("请输入您要更改的商品编号");
int id = sc.nextInt();
System.out.println("请输入您更改后的数量");
int num = sc.nextInt();
if
}
System.out.println("您的商品数量更改完成");
}*/
private static void checkGoods(Goods[] shopCar) {
System.out.println("查询购物车信息如下");
for (int i = 0; i < shopCar.length; i++) {
Goods g = shopCar[i];
if (shopCar[i] != null) {
System.out.println(g.id + "\t\t" + g.name + "\t\t" + g.price + "\t\t" + g.buyNum);
} else {
break;
}
}
}
private static void addGoods(Goods[] shopCar) {
System.out.println("请输入您要添加商品的种类数");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
Goods g = new Goods();
for (int i = 0; i < num; i++) {
System.out.println("请输入商品编号");
int id = sc.nextInt();
g.id = id;
System.out.println("请输入商品名称");
String name = sc.next();
g.name = name;
System.out.println("请输入商品的价格");
double price = sc.nextDouble();
g.price = price;
System.out.println("请输入商品数量");
int n = sc.nextInt();
g.buyNum = n;
for (int j = 0; j < shopCar.length; j++) {
if (shopCar[j] == null) {
shopCar[j] = g;
break;
}
}
}
System.out.println("恭喜您添加商品成功");
}
}
//输出结果截图
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/351588744746118.png "#left")