在java中生成大小为8的字母数字随机和唯一字符串(需要大写字母)

时间:2015-06-29 12:47:30

标签: java

我正在尝试生成大小为8的随机且唯一的字符串,该字符串必须包含数字和大写字母。 请帮我。 例如 AB2CDE11

2 个答案:

答案 0 :(得分:1)

退房:Here is a screenshot并选择最合适的方法!我建议:

RandomStringUtils.randomAlphanumeric(8)

答案 1 :(得分:0)

    /**
     * This method produces a random password with combination of alphabets in lower and Upper case along with numbers
     */

        char[] characterSet={'a', 'b', 'c', 'd',
                'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
                'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        char[] charSetUpper={'A', 'B', 'C', 'D',
                'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
                'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
        char[] numbers={'0', '1', '2', '3', '4',
                '5', '6', '7', '8', '9'};

        List<Character> characters = new ArrayList<Character>();
        StringBuilder sb = new StringBuilder();

        int alphaRand=new Random().nextInt(4);

        alphaRand=alphaRand>0?alphaRand:alphaRand+1;

        for (int loop = 0; loop<alphaRand; loop++) {
            int index = new Random().nextInt(characterSet.length);
            characters.add(characterSet[index]);
        }
        for (int loop = 0; loop<4-alphaRand; loop++) {
            int index = new Random().nextInt(charSetUpper.length);
            characters.add(charSetUpper[index]);
        }
        for (int loop = 0; loop<4; loop++) {
            int index = new Random().nextInt(numbers.length);
            characters.add(numbers[index]);
        }

        while(characters.size()!=0){
            int randPicker = (int)(Math.random()*characters.size());
            sb.append(characters.remove(randPicker));
        }

        String nonce = sb.toString();
        System.out.println(nonce);