This article provides a simple Java code example for generating English character captchas. The code utilizes a Random object to generate random uppercase letters and concatenates them to form a captcha string.

import java.util.Random;

public class EnglishCaptchaGenerator {

    public static void main(String[] args) {
        String captcha = generateCaptcha(6);
        System.out.println(captcha);
    }

    public static String generateCaptcha(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            char c = (char) (random.nextInt(26) + 'A');
            sb.append(c);
        }
        return sb.toString();
    }
}

The generateCaptcha method accepts an integer parameter length specifying the desired length of the captcha. Inside the method, a Random object generates random numbers, which are then converted to uppercase letters by adding them to the ASCII code of 'A'. The loop iterates length times, appending each random letter to a StringBuilder object. Finally, the StringBuilder is converted to a string and returned.

In the main method, the generateCaptcha method is called to generate a captcha of length 6, which is then printed to the console.


原文地址: https://www.cveoy.top/t/topic/o2HZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录