Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class RandomString
- {
- private static final Random RANDOM_GEN = new Random();
- private static final char[] ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
- public static void main(String[] args)
- {
- for (int i = 0; i < 10; i++)
- {
- System.out.println(genRandomString2());
- }
- }
- /**
- * Generates one of the possible 10^16 strings. Each string is equally likely.
- */
- public static String genRandomString()
- {
- StringBuilder sb = new StringBuilder();
- // we iterate for 4 times, each time appending a 4-character string to sb
- for (int i = 0; i < 4; i++)
- {
- // generate a number between 0-9999
- String s = Integer.toString(RANDOM_GEN.nextInt(10000));
- // if the number has less than 4 digits, pad the leading digits with 0s
- for (int j = 0, zeros = 4 - s.length(); j < zeros; j++)
- {
- sb.append('0');
- }
- sb.append(s);
- }
- return sb.toString();
- }
- /**
- * Generates one of the possible 36^16 strings. Each string is equally likely.
- */
- public static String genRandomString2()
- {
- int nAlphabets = ALPHABETS.length;
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < 16; i++)
- {
- // pick a character from the ALPHABETS array at random
- sb.append(ALPHABETS[RANDOM_GEN.nextInt(nAlphabets)]);
- }
- return sb.toString();
- }
- }
Add Comment
Please, Sign In to add comment