购物管理系统java代码
时间: 2023-12-15 18:06:19 浏览: 36
以下是一个简单的超市购物管理系统的Java代码,它涵盖了Java基础语法、面向对象的开发思想、Java如何操作数据库以及集合方面的知识。这个系统可以让用户浏览商品、添加商品到购物车、结账等。
```java
import java.sql.*;
import java.util.*;
public class ShoppingSystem {
private static final String DB_URL = "jdbc:mysql://localhost:3306/shopping_system";
private static final String USER = "root";
private static final String PASS = "password";
private static Connection conn = null;
private static Statement stmt = null;
private static ResultSet rs = null;
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
Scanner scanner = new Scanner(System.in);
List<String> cart = new ArrayList<>();
boolean isShopping = true;
while (isShopping) {
System.out.println("欢迎来到超市购物系统!");
System.out.println("1.浏览商品 2.添加商品到购物车 3.结账 4.退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
browseProducts();
break;
case 2:
addProductToCart(cart);
break;
case 3:
checkout(cart);
break;
case 4:
isShopping = false;
break;
default:
System.out.println("无效的选择,请重新输入!");
break;
}
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
private static void browseProducts() throws SQLException {
String sql = "SELECT * FROM products";
rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double price = rs.getDouble("price");
System.out.println(id + "\t" + name + "\t" + price);
}
}
private static void addProductToCart(List<String> cart) throws SQLException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要添加到购物车的商品ID:");
int productId = scanner.nextInt();
String sql = "SELECT name FROM products WHERE id = " + productId;
rs = stmt.executeQuery(sql);
if (rs.next()) {
String productName = rs.getString("name");
cart.add(productName);
System.out.println(productName + "已添加到购物车!");
} else {
System.out.println("无效的商品ID!");
}
}
private static void checkout(List<String> cart) {
double totalPrice = 0;
System.out.println("您的购物车:");
for (String productName : cart) {
String sql = "SELECT price FROM products WHERE name = '" + productName + "'";
try {
rs = stmt.executeQuery(sql);
if (rs.next()) {
double price = rs.getDouble("price");
System.out.println(productName + "\t" + price);
totalPrice += price;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.println("总价:" + totalPrice);
cart.clear();
}
}
```