Generating a random string of any length method (randomString)

First, create a randomString method you want to use in class. code show as below:

private static String randomString(int length) {
        String xx = "";
        for (short i = '0'; i <= '9'; i++) {
            xx += (char) i;
        }
        for (short i = 'a'; i <= 'z'; i++) {
            xx += (char) i;
        }
        for (short i = 'A'; i <= 'Z'; i++) {
            xx += (char) i;
        }
        char yy[] = new char[length];
        for (int i = 0; i < yy.length; i++) {
            int index = (int) (Math.random() * xx.length());
            yy[i] = xx.charAt(index);
        }
        String result = new String(yy);
        return result;
    }

If you want to generate a string of length 10, to achieve the following:

String shengcheng = randomString(10);
        System.out.println(shengcheng);

It generates a random string of length 10  shengcheng.

Guess you like

Origin www.cnblogs.com/nifengzhe/p/11812000.html