1.使用随机数生成器或其他生成唯一标识符的算法来生成兑换码。
2.创建一个 HashSet 或其他适合存储兑换码的数据结构来确保唯一性。每次生成一个兑换码时,先检查它是否已经存在于 HashSet 中,如果存在则重新生成直到生成一个新的唯一兑换码。
3.循环调用生成兑换码的方法,生成指定数量的兑换码。
4.将生成的兑换码插入到数据库中。这部分需要根据使用的数据库进行具体实现。可以使用 JDBC 连接数据库,并执行插入操作将兑换码写入数据库表中。
import java.util.*;public class CouponCodeGenerator {public static void main(String[] args) {int numOfCodes = 100; Set<String> codes = new HashSet<>();while (codes.size() < numOfCodes) {String code = generateCouponCode();codes.add(code);}insertCodesToDatabase(codes);}private static String generateCouponCode() {String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";StringBuilder code = new StringBuilder();Random random = new Random();for (int i = 0; i < 10; i++) {int index = random.nextInt(characters.length());code.append(characters.charAt(index));}return code.toString();}private static void insertCodesToDatabase(Set<String> codes) {String url = "jdbc:mysql://localhost:3306/mydb"; String username = "root"; String password = "password"; try (Connection connection = DriverManager.getConnection(url, username, password)) {Statement statement = connection.createStatement();for (String code : codes) {String query = "INSERT INTO coupon_codes (code) VALUES ('" + code + "')";statement.executeUpdate(query);}System.out.println("兑换码已成功添加到数据库。");} catch (SQLException e) {e.printStackTrace();}}
}