Guest User

Untitled

a guest
Jan 19th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. public class RandomString
  2. {
  3. private static final Random RANDOM_GEN = new Random();
  4. private static final char[] ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
  5.  
  6. public static void main(String[] args)
  7. {
  8. for (int i = 0; i < 10; i++)
  9. {
  10. System.out.println(genRandomString2());
  11. }
  12. }
  13.  
  14. /**
  15. * Generates one of the possible 10^16 strings. Each string is equally likely.
  16. */
  17. public static String genRandomString()
  18. {
  19. StringBuilder sb = new StringBuilder();
  20. // we iterate for 4 times, each time appending a 4-character string to sb
  21. for (int i = 0; i < 4; i++)
  22. {
  23. // generate a number between 0-9999
  24. String s = Integer.toString(RANDOM_GEN.nextInt(10000));
  25.  
  26. // if the number has less than 4 digits, pad the leading digits with 0s
  27. for (int j = 0, zeros = 4 - s.length(); j < zeros; j++)
  28. {
  29. sb.append('0');
  30. }
  31. sb.append(s);
  32. }
  33. return sb.toString();
  34. }
  35.  
  36. /**
  37. * Generates one of the possible 36^16 strings. Each string is equally likely.
  38. */
  39. public static String genRandomString2()
  40. {
  41. int nAlphabets = ALPHABETS.length;
  42.  
  43. StringBuilder sb = new StringBuilder();
  44. for (int i = 0; i < 16; i++)
  45. {
  46. // pick a character from the ALPHABETS array at random
  47. sb.append(ALPHABETS[RANDOM_GEN.nextInt(nAlphabets)]);
  48. }
  49. return sb.toString();
  50. }
  51. }
Add Comment
Please, Sign In to add comment