当前位置:   article > 正文

随机生成5位大小写字母或者数字_随机生成5个字母

随机生成5个字母

随机生成5位大小写字母或者数字

方法一:生成不重复的

  1. public static void main(String[] args) {
  2. Random rand = new Random();
  3. char[] letters=new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',
  4. 'R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i',
  5. 'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','r',
  6. '0','1','2','3','4','5','6','7','8','9'};
  7. String str = "";
  8. int index;
  9. boolean[] flags = new boolean[letters.length];//默认为false
  10. for(int i=0;i<5;i++){
  11. do{
  12. index = rand.nextInt(letters.length);
  13. }while(flags[index]==true);
  14. char c = letters[index];
  15. str += c;
  16. flags[index]=true;
  17. }
  18. System.out.println(str);
  19. }

方法二:生成重复的,与方法一类似

  1. public static void main(String[] args) {
  2. Random rand = new Random();
  3. char[] letters=new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',
  4. 'R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i',
  5. 'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','r',
  6. '0','1','2','3','4','5','6','7','8','9'};
  7. String str = "";
  8. int index;
  9. boolean[] flags = new boolean[letters.length];//默认为false
  10. for(int i=0;i<5;i++){
  11. do{
  12. index = rand.nextInt(letters.length);
  13. }while(flags[index]==true);
  14. char c = letters[index];
  15. str += c;
  16. flags[index]=true;
  17. }
  18. System.out.println(str);
  19. }

方法三:生成重复的(建议选用此方法)

  1. public static void main(String[] args) {
  2. String str = "";
  3. Random rand = new Random();
  4. for(int i=0;i<5;i++){
  5. int num = rand.nextInt(3);
  6. switch(num){
  7. case 0:
  8. char c1 = (char)(rand.nextInt(26)+'a');//生成随机小写字母
  9. str += c1;
  10. break;
  11. case 1:
  12. char c2 = (char)(rand.nextInt(26)+'A');//生成随机大写字母
  13. str += c2;
  14. break;
  15. case 2:
  16. str += rand.nextInt(10);//生成随机数字
  17. }
  18. }
  19. System.out.println("生成的5个随机验证码是:"+str);
  20. }




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/238772
推荐阅读
相关标签
  

闽ICP备14008679号