简单的购物车系统,实现添加商品,展示商品,修改购买数量,结算购买金额功能。
package com.itheima.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 command=sc.next();
switch (command) {
case "add":
//添加商品到购物车
addCar(shopCar);
break;
case "query":
//查询购物车商品展示
queryCar(shopCar);
break;
case "update":
//修改商品购买数量
updateCar(shopCar);
break;
case "pay":
//结算购买商品的金额
payCar(shopCar);
break;
}
}
}
public static void payCar (Goods[] shopCar) {
//定义一个求和变量累加金额
double money=0;
//遍历购物车数组中的全部对象,累加单价*数量
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);
}
public static void updateCar(Goods[] shopCar) {
while (true){
System.out.println("请输入你要修改商品的id:");
Scanner sc=new Scanner(System.in);
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("修改完成!");
queryCar(shopCar);
break;
}
}
}
public static Goods getGoodsById(Goods[] shopCar,int id){
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;
}
/**
查询购物车中的商品对象的信息,并展示出来
*/
public static void queryCar(Goods[] shopCar) {
System.out.println("=======商品信息查询如下:==========");
System.out.println("编号\t\t\t名称\t\t\t价格\t\t购买数量");
//shopCar[g1,g2,g3,null.....]
for (int i = 0; i < shopCar.length; i++) {
Goods g=shopCar[i];
if (shopCar[i]!=null){
//展示这个商品对象
System.out.println(g.id+"\t\t\t"+g.name+"\t\t\t"+g.price+"\t\t"+g.buyNumber);
}else{
//遍历结束
break;
}
}
}
/**
完成商品添加到购物车的功能
*/
public static void addCar(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 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;
//把这个商品添加到购物车里
//shopCar=[a1,a2,a3,a4,null......]
for (int i = 0; i < shopCar.length; i++) {
if (shopCar[i]==null){
//说明此位置没有元素,把我们新买的商品添加到这个位置即可。
shopCar[i]=g;
break;//结束,因为商品已经存入,不用继续寻找了。
}
}
System.out.println("您的商品:"+g.name+"添加到购物车完成");
}
}
菜单栏
输入添加商品命令
添加商品完成
输入查询购物车商品命令
修改商品数量命令
结算命令