当前位置:   article > 正文

JAVA生成32位随机字符串工具_随机32位字符串生成

随机32位字符串生成

原理就是使用random对象生成随机值,然后根据生成的随机值生成大小写字母或者是数字再拼接成字符串即可,其实准确来说应该是生成任意位数的随机字符串,因为randomSequence的入参size决定了字符串的长度 

  1. import java.util.Random;
  2. public class GeneratorUtil {
  3. private static Random random = new Random();
  4. private static final char ALPHA = 'a';
  5. private static final char NUMBER = '0';
  6. private static final char UPPERCASEALPHA = 'A';
  7. private static final int ALPHABOUND = 26;
  8. private static final int NUMBERBOUND = 10;
  9. private static final int RANDOMTYPEBOUND = 3;
  10. public static String randomSequence(int size){
  11. StringBuffer sequence = new StringBuffer();
  12. for(int i=0;i<size;i++){
  13. sequence.append(getRandomValue());
  14. }
  15. return sequence.toString();
  16. }
  17. private static char getRandomValue(){
  18. int index = random.nextInt(RANDOMTYPEBOUND);
  19. if(index == 0){
  20. return randomAlpha();
  21. }else if(index == 1){
  22. return randomNumber();
  23. }else{
  24. return randomUpperAlpha();
  25. }
  26. }
  27. private static char randomAlpha(){
  28. return randomValue(ALPHA,ALPHABOUND);
  29. }
  30. private static char randomNumber(){
  31. return randomValue(NUMBER,NUMBERBOUND);
  32. }
  33. private static char randomUpperAlpha(){
  34. return randomValue(UPPERCASEALPHA,ALPHABOUND);
  35. }
  36. private static char randomValue(int start,int bound){
  37. int index = random.nextInt(bound);
  38. char next = (char)(start + index);
  39. return next;
  40. }
  41. public static void main(String[] args) {
  42. for(int i=0;i<10;i++){
  43. System.out.println(randomSequence(32));
  44. }
  45. }
  46. }

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/758211
推荐阅读
相关标签
  

闽ICP备14008679号