一、选题
购物车 等级:B
要求:
1.先建立一个文本文件,定义出自己想要的商品。//也可用数据库
以”商品编号,商品名称,商品品牌,价格”格式的文本作为文件的内容。
2.编写程序,定义一个商品类,文件中的内容为该类的所有属性,文件中每一条记录对应该类的每一个实例。当程序启动时,将所有商品从文件或数据库中加载到内存中。
3. 支持多用户.每个用户登录系统后有各自不同的购物车。用户退出系统时,应将购物车的内容存入文件或数据库,用户登录系统后可从文件或数据库中将购物车的商品读入。
4.系统提供“1浏览商品,2添加购物车,3查看购物车,4删除购物车中的商品,5 更购物车中商品的数量,6 结账(生成一条订单,该订单包含用户信息与购物车内商品条目、数量、总价等信息)”种功能。
5.客户可通过鼠标点击(左键点击、右键点击)相应商品条目将商品加入到购物车中(同一种商品可以加入购物车多次,但是只显示一个条目),添加商品后要实时显示购物车中的所有商品价格总和。
6.删除和修改都是针对购物车中的商品而定的,而不是针对已经存在的商品。
二、人员分工
我负责完成了整个购物车系统的设计与实现,包括面向对象设计、类的编写、功能模块的开发、GUI界面的规划调整等任务。
序号 | 完成功能与任务 | 描述 |
1 | 购物车系统GUI界面设计 | 设计并实现了购物车系统的图形用户界面,包括主窗口、商品浏览界面、购物车界面等。 |
2 | 购物车系统 | 设计购物车系统的核心逻辑,包括用户管理、商品管理、购物车管理等内容。 |
三、项目描述
1、项目简介
该项目是一个简单的购物车系统,实现了用户注册、登录、浏览商品、添加商品到购物车、查看购物车、结账等功能。用户可以在系统中注册账号,登录后浏览商品并将商品加入购物车,最终完成结账操作。
2、项目采用技术
- GUI图形界面
- Jsmooth使用
- 文件存储
- 面向对象设计
3、功能需求分析
- 用户注册登录登出
- 添加商品到购物车
- 从购物车移除商品
- 修改购物车中商品数量
- 浏览商品
- 结算总金额
4、项目亮点
- 界面简洁清晰,交互简单,操作性好
- 面向对象设计,逻辑通畅
- .exe文件启动
- 功能较为完备
5、系统细节
- 系统目录
- 系统中包含以下主要对象:
-
这个程序包含了两个包:
ShoppingCart
和ShoppingcartApp
。在
ShoppingCart
包中,我们有以下类: CartItem
: 购物车条目类:
○表示购物车中的商品条目。
ShoppingCartSystem
: 购物车系统类:
○实现了购物车的各种功能,包括加载商品信息、注册用户、用户登录、浏览商品、添加商品到购物车、查看购物车、删除购物车中的商品、更改购物车中商品的数量、结账等功能。
User
: 用户类:
○表示系统中的用户,包括用户名、密码以及购物车中的商品条目列表。
Product
: 产品类:
○表示商品信息,包括商品ID、名称、品牌以及价格。
UserManager
: 用户管理类:
○用于管理用户以及其对应的购物车。 这些类之间的关系是:ShoppingCartSystem
使用了 Product
和 User
类来实现购物车系统功能,User
类又包含了 CartItem
对象来表示购物车中的商品条目。UserManager
类负责管理用户和其对应的购物车。
在 ShoppingcartApp
包中,我们有以下类:
ShoppingCartApp
: 购物车应用程序类:
○包含了 main
方法,用于演示购物车系统的各种功能。
ShoppingCartGUI
: 购物车图形用户界面类:
○实现了一个图形用户界面,允许用户进行注册、登录、浏览商品、管理购物车等操作。
主要的类是 ShoppingCartSystem
,它是整个购物车系统的核心,负责处理商品信息、用户管理以及购物车操作。另外,ShoppingCartApp
中的 main
方法用于演示整个购物车系统的功能,而 ShoppingCartGUI
则提供了一个可视化的用户界面,方便用户进行交互操作。
四、运行结果功能展示
1、用户注册登录:
2、查看商品:
3、添加商品到购物车:
4、删除购物车中的一个商品:5、修改购物车中商品的数量:
6、查看购物车:
7、结算:
五、关键代码
1、购物车条目类
package ShoppingCart;
//购物车条目类
public class CartItem{
private Product product;
private int quantity;
public CartItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public Product getProduct() {
return product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getTotalPrice() {
return product.getPrice() * quantity;
}
}
2、商品类
package ShoppingCart;
//商品类
public class Product {
private int id;
private String name;
private String brand;
private double price;
public Product(int id, String name, String brand, double price) {
this.id = id;
this.name = name;
this.brand = brand;
this.price = price;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getBrand() {
return brand;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return id + ", " + name + ", " + brand + ", " + price;
}
}
3、购物车系统类:
package ShoppingCart;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
//购物车系统类
public class ShoppingCartSystem {
private List<Product> products; // 所有商品列表
private List<User> users; // 所有用户列表
private User currentUser; // 当前登录用户
public ShoppingCartSystem(User user) {
new ArrayList<>();
}
public ShoppingCartSystem() {
this.products = new ArrayList<>();
this.users = new ArrayList<>();
this.currentUser = null;
}
// 加载商品信息
public void loadProducts(String filePath) {
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] data = line.split(",");
int id = Integer.parseInt(data[0]);
String name = data[1];
String brand = data[2];
double price = Double.parseDouble(data[3]);
Product product = new Product(id, name, brand, price);
products.add(product);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 注册用户
public void registerUser(String username, String password) {
User user = new User(username, password);
users.add(user);
}
// 用户登录
public boolean loginUser(String username, String password) {
for (User user : users) {
if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
currentUser = user;
return true;
}
}
return false;
}
// 用户登出
public void logoutUser() {
currentUser = null;
}
// 浏览商品
public void viewProducts() {
System.out.println("Available Products:");
for (Product product : products) {
System.out.println(product);
}
}
// 添加商品到购物车
public void addToCart(int productId, int quantity) {
if (currentUser == null) {
System.out.println("Please login first!");
return;
}
for (Product product : products) {
if (product.getId() == productId) {
currentUser.addToCart(product, quantity);
System.out.println("Added to cart: " + product.getName());
return;
}
}
System.out.println("Product not found!");
}
// 查看购物车
public void viewCart() {
if (currentUser == null) {
System.out.println("Please login first!");
return;
}
List<CartItem> cartItems = currentUser.getCartItems();
System.out.println("User: " + currentUser.getUsername());
System.out.println("Cart Items:");
for (CartItem item : cartItems) {
System.out.println(item.getProduct().getName() + " (x" + item.getQuantity() + ")" + ", $" + item.getTotalPrice());
}
System.out.println("Total Price: $" + currentUser.calculateTotalPrice());
}
public List<Product> getProducts() {
return products;
}
// 删除购物车中的商品
public void removeFromCart(int productId) {
if (currentUser == null) {
System.out.println("Please login first!");
return;
}
List<CartItem> cartItems = currentUser.getCartItems();
for (CartItem item : cartItems) {
if (item.getProduct().getId() == productId) {
currentUser.removeFromCart(item);
System.out.println("Removed from cart: " + item.getProduct().getName());
return;
}
}
System.out.println("Item not found in cart!");
}
// 更改购物车中商品的数量
public void updateCartItemQuantity(int productId, int quantity) {
if (currentUser == null) {
System.out.println("Please login first!");
return;
}
List<CartItem> cartItems = currentUser.getCartItems();
for (CartItem item : cartItems) {
if (item.getProduct().getId() == productId) {
item.setQuantity(quantity);
System.out.println("Updated item quantity: " + item.getProduct().getName());
return;
}
}
System.out.println("Item not found in cart!");
}
// 结账(生成订单并清空购物车)
public void checkout() {
if (currentUser == null) {
System.out.println("Please login first!");
return;
}
double totalPrice = currentUser.calculateTotalPrice();
List<CartItem> cartItems = currentUser.getCartItems();
System.out.println("User: " + currentUser.getUsername());
System.out.println("Cart Items:");
for (CartItem item : cartItems) {
System.out.println(item.getProduct().getName() + " (x" + item.getQuantity() + ")" + ", $" + item.getTotalPrice());
}
System.out.println("Total Price: $" + totalPrice);
// 生成订单,清空购物车
cartItems.clear();
System.out.println("Checkout successful!");
}
public User getCurrentUser() {
return currentUser;
}
// 获取输出信息
public String getOutput() {
if (currentUser == null) {
return "No user logged in.";
} else {
StringBuilder output = new StringBuilder();
output.append("User: " + currentUser.getUsername() + "\n");
output.append("Products:\n");
for (Product product : products) {
output.append(product);
output.append("\n");
}
output.append("Cart Items:\n");
for (CartItem item : currentUser.getCartItems()) {
output.append("Product: " + item.getProduct().getName() + ", Quantity: " + item.getQuantity() + "\n");
}
output.append("Total Price: $" + currentUser.calculateTotalPrice() + "\n");
return output.toString();
}
}
public void logout(UserManager userManager) {
userManager.saveCartsToFile();
}
}
4、用户类:
package ShoppingCart;
import java.util.ArrayList;
import java.util.List;
//用户类
public class User {
private String username;
private String password;
private List<CartItem> cartItems;
public User(String username) {
this.username = username;
}
public User(String username, String password) {
this.username = username;
this.password = password;
this.cartItems = new ArrayList<>();
}
public String getUsername() {
return username;
}
public String getPassword() {
if (password == null) {
// 处理密码为null的情况,可以返回空字符串或者抛出异常
return "";
}
return password;
}
public List<CartItem> getCartItems() {
return cartItems;
}
public void addToCart(Product product, int quantity) {//将指定数量的产品添加到购物车中。这个方法首先遍历购物车中已有的CartItem列表,查找是否已经存在相同的产品。如果找到了相同的产品,则只需要将数量加上新添加的数量即可;否则,将新的CartItem对象添加到购物车中。
for (CartItem item : cartItems) {
if (item.getProduct().getId() == product.getId()) {
item.setQuantity(item.getQuantity() + quantity);
return;
}
}
cartItems.add(new CartItem(product, quantity));
}
public void removeFromCart(CartItem item) {
cartItems.remove(item);
}
public double calculateTotalPrice() {
double totalPrice = 0;
for (CartItem item : cartItems) {
totalPrice += item.getTotalPrice();
}
return totalPrice;
}
@Override
public String toString() {
return "User: " + username + "\n" + "Cart Items: " + cartItems.size();
}
}
5、用户管理类:
package ShoppingCart;
import java.io.*;
import java.util.*;
class UserManager {
private Map<String, ShoppingCartSystem> userCarts;
public UserManager() {
userCarts = new HashMap<>();
loadCartsFromFile();
}
public void addUser(User user) {
ShoppingCartSystem cart = new ShoppingCartSystem();
userCarts.put(user.getUsername(), cart);
}
public ShoppingCartSystem getCartByUsername(String username) {
return userCarts.get(username);
}
// 在用户退出系统时将购物车的内容存入文件
public void saveCartsToFile() {
try {
FileOutputStream fileOut = new FileOutputStream("carts.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(userCarts);
out.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 在用户登录系统时从文件中读取购物车的商品
private void loadCartsFromFile() {
try {
FileInputStream fileIn = new FileInputStream("carts.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
userCarts = (Map<String, ShoppingCartSystem>) in.readObject();
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException e) {
// 如果文件不存在或读取失败,则不进行任何操作
}
}
}
6、购物车App主类:
package ShoppingcartApp;
import ShoppingCart.ShoppingCartSystem;
public class ShoppingCartApp {
public static void main(String[]args) {
ShoppingCartSystem system = new ShoppingCartSystem();
system.loadProducts("products.txt");
// 注册用户
system.registerUser("user1", null);
system.registerUser("user2", null);
// 用户登录
system.loginUser("user1", null);
// 浏览商品
system.viewProducts();
// 添加商品到购物车
system.addToCart(1, 2);
system.addToCart(2, 1);
// 查看购物车
system.viewCart();
// 删除购物车中的商品
system.removeFromCart(1);
// 更改购物车中商品的数量
system.updateCartItemQuantity(2, 3);
// 结账
system.checkout();
// 用户登出
system.logoutUser();
}
}
7、GUI界面:
package ShoppingcartApp;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ShoppingCart.ShoppingCartSystem;
import java.util.*;
import ShoppingCart.User;
import ShoppingCart.CartItem;
import ShoppingCart.Product;
public class ShoppingCartGUI extends JFrame {
private ShoppingCartSystem system;
private JTextArea outputTextArea;
public ShoppingCartGUI() {
system = new ShoppingCartSystem();
system.loadProducts("products.txt");
// 创建界面组件
JLabel titleLabel = new JLabel("Shopping Cart App");
titleLabel.setFont(new Font("Arial", Font.BOLD, 24));
JLabel usernameLabel = new JLabel("Username:");
JTextField usernameTextField = new JTextField(20);
JLabel passwordLabel = new JLabel("Password:");
JPasswordField passwordField = new JPasswordField(20);
JButton registerButton = new JButton("Register");
JButton loginButton = new JButton("Login");
JButton logoutButton = new JButton("Logout");
JTextArea productsTextArea = new JTextArea(15, 50);
JButton addToCartButton = new JButton("Add to Cart");
JButton removeFromCartButton = new JButton("Remove from Cart");
JButton updateQuantityButton = new JButton("Update Quantity");
JButton viewCartButton = new JButton("View Cart");
JButton checkoutButton = new JButton("Checkout");
JButton viewProductsButton = new JButton("View Products");
outputTextArea = new JTextArea(10, 50);
// 设置布局
setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.add(titleLabel);
add(topPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new FlowLayout());
centerPanel.add(usernameLabel);
centerPanel.add(usernameTextField);
centerPanel.add(passwordLabel);
centerPanel.add(passwordField);
centerPanel.add(registerButton);
centerPanel.add(loginButton);
centerPanel.add(logoutButton);
centerPanel.add(productsTextArea);
JScrollPane productsScrollPane = new JScrollPane(productsTextArea);
centerPanel.add(productsScrollPane);
centerPanel.add(addToCartButton);
centerPanel.add(removeFromCartButton);
centerPanel.add(updateQuantityButton);
centerPanel.add(viewCartButton);
centerPanel.add(checkoutButton);
centerPanel.add(viewProductsButton);
add(centerPanel, BorderLayout.CENTER);
JScrollPane outputScrollPane = new JScrollPane(outputTextArea);
add(outputScrollPane, BorderLayout.SOUTH);
// 设置事件监听器
registerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameTextField.getText();
String password = new String(passwordField.getPassword());
system.registerUser(username, password);
outputTextArea.append(system.getOutput() + "\n");
updateUI();
}
});
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameTextField.getText();
String password = new String(passwordField.getPassword());
boolean loggedIn = system.loginUser(username, password);
if (loggedIn) {
outputTextArea.append("User logged in: " + username + "\n");
} else {
outputTextArea.append("Invalid username or password\n");
}
updateUI();
}
});
viewProductsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
system.viewProducts();
outputTextArea.append("Available Products:\n");
for (Product product : system.getProducts()) {
outputTextArea.append(product.toString() + "\n");
}
}
});
addToCartButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (system.getCurrentUser() == null) {
outputTextArea.append("Please login first!\n");
return;
}
int productId = Integer.parseInt(JOptionPane.showInputDialog("Enter Product ID:"));
int quantity = Integer.parseInt(JOptionPane.showInputDialog("Enter Quantity:"));
system.addToCart(productId, quantity);
outputTextArea.append("Added to cart: " + productId + ", Quantity: " + quantity + "\n");
outputTextArea.append("Updated Cart Items:\n");
outputTextArea.append(system.getOutput() + "\n");
updateUI();
}
});
removeFromCartButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (system.getCurrentUser() == null) {
outputTextArea.append("Please login first!\n");
return;
}
int productId = Integer.parseInt(JOptionPane.showInputDialog("Enter Product ID:"));
system.removeFromCart(productId);
outputTextArea.append("Removed from cart: " + productId + "\n");
updateUI();
}
});
updateQuantityButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (system.getCurrentUser() == null) {
outputTextArea.append("Please login first!\n");
return;
}
int productId = Integer.parseInt(JOptionPane.showInputDialog("Enter Product ID:"));
int quantity = Integer.parseInt(JOptionPane.showInputDialog("Enter Quantity:"));
system.updateCartItemQuantity(productId, quantity);
outputTextArea.append("Updated item quantity: " + productId + ", Quantity: " + quantity + "\n");
updateUI();
}
});
viewCartButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (system.getCurrentUser() == null) {
outputTextArea.append("Please login first!\n");
return;
}
system.viewCart();
outputTextArea.append("Cart Items:\n");
for (CartItem item : system.getCurrentUser().getCartItems()) {
outputTextArea.append("Product: " + item.getProduct().getName() + ", Quantity: " + item.getQuantity() + "\n");
}
outputTextArea.append("Total Price: $" + system.getCurrentUser().calculateTotalPrice() + "\n");
updateUI();
}
});
checkoutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (system.getCurrentUser() == null) {
outputTextArea.append("Please login first!\n");
return;
}
system.checkout();
outputTextArea.append(system.getOutput() + "\n");
updateUI();
}
});
// 设置窗口属性
setTitle("Shopping Cart App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setResizable(false);
setVisible(true);
setLocation(500, 200);
setBackground(Color.blue);
}
private void updateUI() {
if (system.getCurrentUser() == null) {
outputTextArea.setText("");
}
}
public static void main(String[] args) {
new ShoppingCartGUI();
}
}
六、总结
6.1 总结:
- 在本次课程设计中,我完成了购物车系统的整体设计与实现,通过面向对象的思想,合理划分了各个类的职责,并且实现了系统的核心功能。在开发过程中,遇到了一些技术难点,但通过不断地思考和学习,最终找到了解决方案,完成了系统的开发。
6.2 展望:
- 在未来,可以进一步优化系统的用户交互体验,提供更友好的界面和更丰富的功能。另外,可以考虑引入数据库存储商品和用户信息,实现持久化存储,提高系统的稳定性和扩展性。
-
七、遇到的困难及解决方法
-
Q1:在将java文件导出为.jar文件时无法打开
A1:在导出的过程中没有看到下一步直接导出,没有指定主要的Main类,然后出来的界面刚开始指定是ShoppingCartApp类为主类,但jar还是没法打开,发现用ShoppingCartGUI为主类就可以了。
Q2:在刚开始导出为.jar时打开无法显示所有功能,出现缺失
A2:后来搜索发现是因为GUI设定的尺寸太小,没办法在屏幕显示出所有的组件。将GUI中setsize改成合适大小就能运行了。
Q3:在将.jar转换成.exe文件时遇到问题,下了三个软件exe4j和launch4j都无法转换,后来学习了Jsmooth,就转换成功了。