关于java:如何创建5位数字和数字组合的随机数

How to create Random number with 5 digit combined of number and charter

我想生成这样的随机数

  • ADF1845CFT

  • ADF1864ATY

  • ADF18AT65Y

Note: There I FIX the ADF18 I want only take the next 5 digit with number and charter

我成功创建了带数字的5位数字

我正在使用各种解决方案

  • 如何组合随机数矩阵

  • 具有给定长度的Java随机数

等方法

通过这些方法,我创建了成功的随机5位数字。

任何帮助欣赏......


你可以使用随机UUID ......

例:

1
2
3
final String randomCode = UUID.randomUUID().toString();
// or you can play with the len...
final String randomCode2 = UUID.randomUUID().toString().substring(0, 5);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.Random;

public class MyStringRandomGen {

private static final String CHAR_LIST =
   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final int RANDOM_STRING_LENGTH = 5;// change the number as u want.

/**
 * This method generates random string
 * @return
 */

public String generateRandomString(){

    StringBuffer randStr = new StringBuffer();
    for(int i=0; i<RANDOM_STRING_LENGTH; i++){
        int number = getRandomNumber();
        char ch = CHAR_LIST.charAt(number);
        randStr.append(ch);
    }
    return randStr.toString();
}

/**
 * This method generates random numbers
 * @return int
 */

private int getRandomNumber() {
    int randomInt = 0;
    Random randomGenerator = new Random();
    randomInt = randomGenerator.nextInt(CHAR_LIST.length());
    if (randomInt - 1 == -1) {
        return randomInt;
    } else {
        return randomInt - 1;
    }
}

public static void main(String a[]){
    MyStringRandomGen msr = new MyStringRandomGen();
    System.out.println(msr.generateRandomString());
    System.out.println(msr.generateRandomString());
    System.out.println(msr.generateRandomString());
    System.out.println(msr.generateRandomString());
    System.out.println(msr.generateRandomString());
    System.out.println(msr.generateRandomString());
    System.out.println(msr.generateRandomString());
}
}


1
2
3
4
5
6
7
8
9
10
11
   String random5Digts = UUID.randomUUID().toString().substring(0, 5);
   String randomNumber="ADF18"+random5Digts;
   //code to change lower letters to uppercase
   StringBuilder sb = new StringBuilder(randomNumber);
   for (int index = 0; index < sb.length(); index++) {
       char c = sb.charAt(index);
       if (Character.isLowerCase(c)) {
           sb.setCharAt(index, Character.toUpperCase(c));
       }
   }
   System.out.println(sb.toString());

你可以使用apache commons-lang RandomStringUtils.randomAlphanumberic

1
"ADF18" + RandomStringUtils.randomAlphanumberic(5);