Java generates random CAPTCHA code, which is confused.

import java.util.Arrays;
import java.util.Random;

public class VerificationCode {
    public static void main(String[] args) {
        String[] CHARS = { "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L",
                "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
        boolean[] charFlags = new boolean[CHARS.length];
        String[] verifyCodes = new String[6];

        Random ran = new Random();
        for (int i = 0; i < verifyCodes.length; iPP) {
            int index;
            do {
                index = ran.nextInt(CHARS.length);
            } while (charFlags[index]);
            verifyCodes[i] = CHARS[index];
            charFlags[index] = true;
        }
        //   

        System.out.print(":");
        for (int i = 0; i < verifyCodes.length; iPP) {
            System.out.print(verifyCodes[i]);
        }
    }
}

Mar.06,2021

which line does not understand?
this declares an array of CHARS
charFlags values that correspond to whether each char has been used. (the purpose here is that the generated CAPTCHA will not have repetitive characters such as two A repeats in AA1234,.)
verifyCodes is the resulting array of CAPTCHA. The logical translation of the
code means:
take one character at a time from the CHARS to see if the character has been used and put it into the final CAPTCHA array verifyCodes if it has not been used. Then take the next one, and if the character extracted from the CHARS has already been used, then randomly generate a subscript and fetch a new character. Until you get 6 characters that are not repeated.


it is inefficient to do a double loop. If the CAPTCHA is longer, someone may not appear for a long time. I don't know why the author did this. For better randomness? the core of the original code is to avoid repeating the same character

change it to this way, it will be easy to understand:

import java.util.Arrays;
import java.util.Random;

public class VerificationCode {
    public static void main(String[] args) {
        char[] CHARS = { '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L',
                'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y' };
        char[] verifyCodes = new char[6];

        Random ran = new Random();
        for (int i = 0; i < verifyCodes.length; iPP) {
            verifyCodes[i] = CHARS[ran.nextInt(CHARS.length)];
        }

        System.out.print(":");
        System.out.print(new String(verifyCodes));
    }
}
Menu