选择菜单/购买商品/查看购物车、付款、退出、返回上一层、同一购物车商品实现叠加、模拟登录账号、等等功能
第一种(不含登录)
定义1个商品父类 3个子类
/*
* 商品类*/
public class Goods {
private String name; //商品名字
private int price; //商品价格
private int number; //商品数量
public Goods(String name, Integer price, Integer number) {
this.name = name;
this.price = price;
this.number = number;
}
public Goods() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
", number=" + number +
'}';
}
}
/*
* 调味品*/
public class Condiments extends Goods{
public Condiments(String name, Integer price, Integer number) {
super(name, price, number);
}
public Condiments() {
}
}
/*
* 日用品类*/
public class Daily extends Goods{
public Daily(String name, Integer price, Integer number) {
super(name, price, number);
}
public Daily() {
}
}
/*
* 食品类*/
public class Foods extends Goods{
public Foods(String name, Integer price, Integer number) {
super(name, price, number);
}
public Foods() {
}
}
一个方法类:
/*
* 商城功能实现类*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Function {
/*
* 三个对象数组*/
Condiments condiments1 = new Condiments("花椒", 10, 0);
Condiments condiments2 = new Condiments("盐", 20, 0);
Condiments condiments3 = new Condiments("糖", 30, 0);
Condiments[] condiments = {condiments1, condiments2, condiments3}; //调味对象数组
Daily daily1 = new Daily("洗脸盆", 10, 0);
Daily daily2 = new Daily("香皂", 20, 0);
Daily daily3 = new Daily("洗发水", 30, 0);
Daily[] dailies = {daily1, daily2, daily3}; //日用对象数组
Foods foods1 = new Foods("面包", 10, 0);
Foods foods2 = new Foods("火腿肠", 20, 0);
Foods foods3 = new Foods("鸡腿", 30, 0);
Foods[] foods = {foods1, foods2, foods3}; //食品对象数组
public ArrayList<Goods> carsList = new ArrayList<>(); //购物车集合
public Scanner scanner = new Scanner(System.in);
public void viewMenu() { //展示菜单功能
Scanner scanner = new Scanner(System.in);
System.out.println("--------欢迎进入欣知商城--------");
System.out.println("请选择您要进入的(请输入1~6进入不同的区域)");
System.out.println("1:日用品 2:食品 3:调味品 4:查看购物车 5:付款 6:放弃购买");
int i = scanner.nextInt();
switch (i) {
case 1:
viewCommodity(dailies); //展示具体分类的商品详情方法
break;
case 2:
viewCommodity(foods);
break;
case 3:
viewCommodity(condiments);
break;
case 4:
viewCar(carsList);
break;
case 5:
pay(carsList);
break;
case 6:
System.out.println("欢迎下次光临");
System.exit(0); //结束虚拟机
break;
default:
System.out.println("输入错误,请重写输入");
break;
}
}
public void viewCommodity(Goods[] goods) { //展示具体分类的商品详情
int count = 1;
System.out.print("请输入购买的商品:");
for (int i = 0; i < goods.length; i++) {
System.out.print((count++) + "." + goods[i].getName() + "-----" + goods[i].getPrice() + "元 ");
}
System.out.println("请输入购买商品");
int i = scanner.nextInt();
switch (i) { //判断购买的商品
case 1:
viewCommodity1(0, goods);
break;
case 2:
viewCommodity1(1, goods);
break;
case 3:
viewCommodity1(2, goods);
break;
default:
System.out.println("输入错误");
break;
}
}
public void viewCommodity1(int a, Goods[] goods) { //具体商品购买流程 以及调用添加购物车方法
System.out.println("请输入购买数量");
int i = scanner.nextInt();
System.out.println(i + "个" + goods[a].getName() + "已加入购物车");
addCar2(goods[a], carsList, i);
viewLevel2(goods); //二级菜单
}
public void addCar2(Goods goods, ArrayList<Goods> carsList, int newnum) { //判断购物车里是否有同一商品第二步
int index = addCar(goods, carsList);
if (index != -1) {
int oldNum = carsList.get(index).getNumber();
carsList.get(index).setNumber(oldNum + newnum);
} else {
goods.setNumber(newnum);
carsList.add(goods);
}
}
public int addCar(Goods goods, ArrayList<Goods> carsList) { //判断购物车里是否有同一商品第一步
for (int i = 0; i < carsList.size(); i++) { //遍历购物车集合
String name = carsList.get(i).getName(); //
if (name.equals(goods.getName())) {
return i;
}
}
return -1;
}
public void viewCar(ArrayList<Goods> carsList) { //展示购物车
if (carsList.isEmpty()) {
System.out.println("请购买商品后再查看购物车");
} else {
System.out.println("---------购物车列表---------");
for (int i = 0; i < carsList.size(); i++) {
System.out.println(carsList.get(i).getName() + "---" + carsList.get(i).getPrice() + "元" + "---" + carsList.get(i).getNumber() + "个");
}
}
}
public void viewLevel2(Goods[] goods) { //二级菜单 返回主菜单/返回上一层/付款
System.out.println("购物完毕 输入1返回主菜单 2返回上一层 0结束购物并付款");
int complete = scanner.nextInt();
switch (complete) {
case 1:
viewMenu();
break;
case 2:
viewCommodity(goods);
break;
case 0:
pay(carsList);
break;
default:
System.out.println("输入错误,请输入0~2");
break;
}
}
public void pay(ArrayList<Goods> carsList) { //付款
int sumPrice = 0; //总价格
int paymentAmount = 0;//付款
if (carsList.isEmpty()) { //判断是否为空
System.out.println("请购买商品后再付款");
}
for (Goods a : carsList) {
sumPrice += a.getNumber() * a.getPrice(); //计算总价
}
System.out.println("总价格为:" + sumPrice + "元 已付款:" + paymentAmount + "元 " + "\n 请付款:");
paymentAmount = scanner.nextInt();
while (paymentAmount < sumPrice) {
System.out.println("您的付款金额不足 还差:" + (paymentAmount - sumPrice) + "元 " +
"\n总价格为:" + sumPrice + "元 已付款:" + paymentAmount + "元 " + "\n请付款:");
int money1 = scanner.nextInt();
paymentAmount += money1;
}
if (paymentAmount >= sumPrice) {
System.out.println("支付成功 找零:" + (paymentAmount - sumPrice) + "元 ");
carsList.clear(); //清空购物车商品
}
}
}
一个测试类:
/*
* 测试类*/
public class Text {
public static void main(String[] args) {
Function function = new Function();
while (true){
function.viewMenu();
}
}
}
结束
第二种:
一个产品类:
/*
* 产品类
* */
public class Product {
private String name; //名字
private double price; //价格
public Product() {
}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
一个购物车类
/*
*
* 购物车类*/
public class ShoppingCart {
private Product product; //产品
private int quantity; //数量
public ShoppingCart(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public ShoppingCart() {
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "ShoppingCart{" +
"product=" + product +
", quantity=" + quantity +
'}';
}
}
用户类:
/*
*
* 用户类*/
public class User {
private String username; //用户名
private String passwaord;//密码
private Integer account; //账户金额
public User() {
}
public User(String username, String passwaord, Integer account) {
this.username = username;
this.passwaord = passwaord;
this.account = account;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswaord() {
return passwaord;
}
public void setPasswaord(String passwaord) {
this.passwaord = passwaord;
}
public Integer getAccount() {
return account;
}
public void setAccount(Integer account) {
this.account = account;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", passwaord='" + passwaord + '\'' +
", account=" + account +
'}';
}
}
一个方法接口:
package Service;
import Pojo.Product;
import Pojo.ShoppingCart;
import Pojo.User;
import java.util.List;
// mainServie 接口
public interface mainServie {
User user();
Boolean Login(User user);
List<Product> ri();
List<Product> food();
List<Product> tw();
void addCat(Product product, int quantity);
void pay();
void viewCart();
}
接口实现类:
package Service;
import Pojo.Product;
import Pojo.ShoppingCart;
import Pojo.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*
* main接口实现类
* */
public class mainServiceImpl implements mainServie {
private static Scanner scanner = new Scanner(System.in);
ArrayList<ShoppingCart> shoppingCarts = new ArrayList<>(); //购物车集合
User userSql = new User("admin", "123456", 9999999); //声明用户对象并赋值 模拟数据库中的用户1
@Override
public User user() { //user方法
System.out.println("请输入账号");
String username = scanner.nextLine();
System.out.println("请输入密码");
String psd = scanner.nextLine();
User user = new User(username, psd, null); //声明一个user对象并赋值
return user;
}
/*
* 登录操作
*/
@Override
public Boolean Login(User user) { //login登录方法 参数为user对象
if (userSql.getUsername().equals(user.getUsername())) { //俩对象用户名验证
if (userSql.getPasswaord().equals(user.getPasswaord())) { //再次验证密码
System.out.println("登录成功");
return true;
} else {
System.out.println("密码错误!");
}
} else {
System.out.println("账号错误,请重新输入!");
}
return false;
}
@Override
public List<Product> ri() { //日用品lis列表
List<Product> ri = new ArrayList<>();
ri.add(new Product("香皂", 10.0));
ri.add(new Product("洗发水", 20.0));
ri.add(new Product("洗脸盆", 30.0));
return ri;
}
@Override
public List<Product> food() {
List<Product> food = new ArrayList<>();
food.add(new Product("面包", 10.0));
food.add(new Product("火腿肠", 20.0));
food.add(new Product("跳跳糖", 30.0));
return food;
}
@Override
public List<Product> tw() {
List<Product> tw = new ArrayList<>();
tw.add(new Product("十三香", 15.0));
tw.add(new Product("老干妈", 11.0));
tw.add(new Product("花椒面", 3.0));
return tw;
}
@Override
public void addCat(Product product, int quantity) { //添加到购物车方法
ShoppingCart shoppingCart = new ShoppingCart(product, quantity);
shoppingCarts.add(shoppingCart);
System.out.println(quantity + "件 " + product.getName() + " 成功加入购物车~~");
System.out.println("购物完毕输入1返回主菜单2返回上一层输入0结束购物并付款");
int choice = scanner.nextInt();
switch (choice) {
case 1:
// 返回主菜单
boolean flag = true; // 设置标志位以进入主菜单循环
break;
case 2:
return;
case 0:
// 结束购物并付款的逻辑
pay();
break;
default:
System.out.println("无效的选项,请重新选择。");
}
}
@Override
public void pay() { //付款方法
double totalPrice = calculateTotalPrice();//调用calculateTotalPrice计算总价方法
displayCartItems(totalPrice);
Integer accountPrice = userSql.getAccount();
System.out.println("请输入付款金额,账户余额(" + accountPrice + ")" + ":");
double payment = scanner.nextDouble();
if (payment < totalPrice) {
boolean w = true;
while (w) {
System.out.println("付款金额不足!");
System.out.println("应付:" + payment + " 还差" + (payment - totalPrice));
int payment2 = scanner.nextInt();
payment += payment2;
if (payment >=totalPrice) {
w = false;//成功变为false 不在循环
System.out.println("付款成功,找零" + (payment - totalPrice) + "元");
}
}
}
double change = payment - totalPrice;
System.out.println("找零金额:" + change + " 【账户余额(" + (accountPrice - totalPrice) + ")】");
// 清空购物车
shoppingCarts.clear();
}
public double calculateTotalPrice() { //计算购物车总价方法
double totalPrice = 0.0;
for (ShoppingCart cart : shoppingCarts) {
totalPrice += cart.getProduct().getPrice() * cart.getQuantity();
}
return totalPrice;
}
public void displayCartItems(double totalPrice) { //显示购物车清单计算方法
System.out.println("购物车清单:");
for (ShoppingCart cart : shoppingCarts) { //增强for循环写法遍历 shoppingCarts
Product product = cart.getProduct();
int quantity = cart.getQuantity();
double subtotal = product.getPrice() * quantity;
System.out.println(product.getName() + " x " + quantity + " = " + subtotal);
}
System.out.println("总价:" + totalPrice);
}
@Override
public void viewCart() { //展示购物方法
if (shoppingCarts.isEmpty()) {
System.out.println("购物车为空!");
return;
}
System.out.println("-----购物车清单-----");
for (int i = 0; i < shoppingCarts.size(); i++) {
ShoppingCart cart = shoppingCarts.get(i);
System.out.println("商品名称: " + cart.getProduct().getName());
System.out.println("商品数量: " + cart.getQuantity());
System.out.println("商品单价: " + cart.getProduct().getPrice());
System.out.println("--------------------");
}
double totalPrice = calculateTotalPrice();
System.out.println("总价: " + totalPrice);
}
}
主菜单类:
import Pojo.Product;
import Pojo.ShoppingCart;
import Pojo.User;
import Service.mainServiceImpl;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
mainServiceImpl mainService = new mainServiceImpl(); //创建mainService对象
boolean flag = false;
while (true) {
User user = mainService.user();
Boolean login = mainService.Login(user);
if (login) {
flag = true;
break;
}
}
if (flag) {
while (true) {
System.out.println();
System.out.println("-----欢迎来到欣知商城,请选择以下操作:-----");
System.out.println("1. 日用品");
System.out.println("2. 食品");
System.out.println("3. 调味品");
System.out.println("4. 查看购物车");
System.out.println("5. 付款");
System.out.println("6. 放弃购买");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
System.out.print("请选择购买的商品:");
int countRi = 1;
for (Product r : mainService.ri()) {
System.out.print(countRi++ + ": " + r.getName() + " " + r.getPrice() + "元、");
}
System.out.println();
System.out.println("请输入品名:");
int selectedProductRi = scanner.nextInt();
System.out.println("请选择数量");
int quantityRi = scanner.nextInt();
Product selectedRi = mainService.ri().get(selectedProductRi - 1);//get方法找到商品 通过索引-1
mainService.addCat(selectedRi, quantityRi); //调用添加购物车addcar方法将商品和数量加入
break;
case 2:
System.out.print("请选择购买的商品:");
int countFood = 1;
for (Product f : mainService.food()) {
System.out.print(countFood++ + ": " + f.getName() + " " + f.getPrice() + "元、");
}
System.out.println();
System.out.println("请输入品名:");
int selectedProductF = scanner.nextInt();
System.out.println("请选择数量");
int quantityF = scanner.nextInt();
Product selectedF = mainService.food().get(selectedProductF - 1);
mainService.addCat(selectedF, quantityF);
break;
case 3:
System.out.print("请选择购买的商品:");
int countTw = 1;
for (Product t : mainService.tw()) {
System.out.print(countTw++ + ": " + t.getName() + " " + t.getPrice() + "元、");
}
System.out.println();
System.out.println("请输入品名:");
int selectedProductT = scanner.nextInt();
System.out.println("请选择数量");
int quantityT = scanner.nextInt();
Product selectedT = mainService.tw().get(selectedProductT - 1);
mainService.addCat(selectedT, quantityT);
break;
case 4:
mainService.viewCart(); //展示购物车
break;
case 5:
mainService.pay(); //付款
break;
case 6:
System.out.println("欢迎下次光临");
System.exit(0); // 退出程序
break;
default:
System.out.println("无效的选项,请重新选择。");
}
}
}
}
}
结束:
第三种:
调味品类:
package xinzhi666;
import Xinzhisop.Shop;
/*
*调味品类 */
public class Condiments extends Goods {
public Condiments(String name, Double price) {
super(name, price);
}
}
日用品类:
//日用品类
public class Dailynecessities extends Goods {
public Dailynecessities(String name, Double price) {
super(name, price);
}
}
食品类:
/*
* 食品类*/
public class Food extends Goods {
public Food(String name, Double price) {
super(name, price);
}
}
父类商品类:
//商品类
public class Goods {
private String name;
private Double price;
public Goods() {
}
public Goods(String name, Double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
方法类:
import java.util.*;
/*
* 客户端类 实现方法*/
public class Client {
public List<Goods> dailynecessities = new ArrayList<>(); //日用品集合
public List<Goods> foodList = new ArrayList<>(); //食物集合
public List<Goods> condiments = new ArrayList<>(); //调味品集合
public List<Map<String, Object>> carList = new ArrayList<>(); //购物车集合
public Scanner scanner = new Scanner(System.in); //扫描仪对象
public void main(String[] args) {
init(dailynecessities, foodList, condiments);
while (true) {
Integer choose = choose();
viewSwitch(choose);
}
}
public int choose() {
System.out.println("-------------欢迎使用欣知商城-------------");
System.out.println("请您选择要进入的(请输入1~6进入不同的区域)\n" +
"1.日用品 2.食品 3.调味品 4.查看购物车 5.付款 6.放弃购买");
int i = scanner.nextInt();
return i;
}
public int printList(List<Goods> list) {
System.out.print("请选择购买的商品:");
for (int i = 0; i < list.size(); i++) {
Goods goods = list.get(i);
System.out.print(i + 1 + "." + goods.getName() + "---" + goods.getPrice() + "元"+" ");
}
System.out.println();
int i = scanner.nextInt();
while (!(i >= 1 && i <= list.size())) {
System.out.println("输入错误");
i = scanner.nextInt();
}
return i-1;
}
public int select() {
System.out.println(" 输入1返回主菜单、输入2返回上一层、输入0、结束购物并付款");
return scanner.nextInt();
}
public List<Map<String, Object>> setSingleGoods(List<Map<String, Object>> carList, Goods goods, Integer num) {
Map<String, Object> map = new HashMap<>();
map.put("商品名称", goods.getName());
map.put("商品价格", goods.getPrice());
map.put("购买数量", num);
carList.add(map);
System.out.println(num+"个"+goods.getName()+"成功加入购物车");
return carList;
}
public void init(List<Goods> dailynecessities, List<Goods> foodList, List<Goods> condiments) {
Goods dailynecessities1 = new Dailynecessities("香皂", 10.0);
Goods dailynecessities2 = new Dailynecessities("洗发水", 20.0);
Goods dailynecessities3 = new Dailynecessities("洗脸盆", 30.0);
dailynecessities.add(dailynecessities1);
dailynecessities.add(dailynecessities2);
dailynecessities.add(dailynecessities3);
Goods food1 = new Food("面包", 5.0);
Goods food2 = new Food("鸡腿", 8.0);
Goods food3 = new Food("火腿肠", 2.0);
foodList.add(food1);
foodList.add(food2);
foodList.add(food3);
Goods condiments1 = new Condiments("老干妈", 10.0);
Goods condiments2 = new Condiments("十三香", 15.0);
Goods condiments3 = new Condiments("味精", 19.0);
condiments.add(condiments1);
condiments.add(condiments2);
condiments.add(condiments3);
}
public Integer buyNumber() {
System.out.println("请输入购买数量");
return scanner.nextInt();
}
public void viewSwitch(Integer number) { //视图
switch (number) {
case 1:
Integer integer = printList(dailynecessities);
Goods goods = dailynecessities.get(integer);
Integer buynumber = buyNumber();
setSingleGoods(carList,goods,buynumber);
doubleChoose(select(), 1);
break;
case 2:
Integer integer1 =printList(foodList);
Goods goods1 = foodList.get(integer1);
Integer buynumber1 = buyNumber();
setSingleGoods(carList,goods1,buynumber1);
doubleChoose(select(), 2);
break;
case 3:
Integer integer2 =printList(condiments);
Goods goods2= condiments.get(integer2);
Integer buynumber2 = buyNumber();
setSingleGoods(carList,goods2,buynumber2);
doubleChoose(select(), 3);
break;
case 4:
printfcar(carList);
break;
case 5:
Payment(carList);
break;
case 6:
System.exit(0);
default:
System.out.println("输入编号有误");
break;
}
}
public void printfcar(List<Map<String, Object>> list){ //打印购物车
if(list.size()==0){
System.out.println("您未购买商品请购买后查看");
}
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = list.get(i);
System.out.println("已购买:");
System.out.print("商品"+(i+1)+" ");
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.print(entry.getKey() +":" + entry.getValue()+" ");
}
System.out.println();
}
}
public void Payment(List<Map<String, Object>> carList) { //付款
int paymentAmount = 0; //已付款
Double sumPrice=0.0; //应付款
for(int i = 0;i < carList.size();i++) {
Map<String, Object> map = carList.get(i);
String shopPirce = map.get("商品价格").toString();
String shopNum = map.get("购买数量").toString();
Double b = Double.valueOf(shopPirce);
Double c = Double.valueOf(shopNum);
Double i1 = b * c;
sumPrice += i1;
}
System.out.println("总价格为" + sumPrice + "元 已付款" + paymentAmount);
System.out.println(" 请付款 :");
paymentAmount= scanner.nextInt();
if (paymentAmount > sumPrice) {
System.out.println("支付成功 找零" + (paymentAmount - sumPrice));
carList.clear(); //清空购物车商品
} else if (paymentAmount < sumPrice) {
while (paymentAmount < sumPrice) {
System.out.println("您的付款金额不足 还差" + (paymentAmount - sumPrice));
System.out.println("总价格为" + sumPrice + "元 已付款" + paymentAmount);
System.out.println("请付款");
int money1 = scanner.nextInt();
paymentAmount += money1;
}
System.out.println("支付成功 找零" + (paymentAmount - sumPrice));
} else {
System.out.println("支付成功 找零" + (paymentAmount - sumPrice));
carList.clear();
}
}
public void doubleChoose(Integer number, int tpye) { //二次选择
switch (number) {
case 1:
break;
case 2:
viewSwitch(tpye);
break;
case 0:
Payment(carList);
break;
default:
System.out.println("输入有误,请重新输入");
break;
}
}
}
结束
以上就是3种不同方案的商城小案例 只是分享
不足之处欢迎指出!!
感谢大家!!