Java random number with given length

This question already has an answer here:

  • How do I generate random integers within a specific range in Java? 57 answers

  • Generate a number in the range from 100000 to 999999 .

    // pseudo code
    int n = 100000 + random_float() * 900000;
    

    I'm pretty sure you have already read the documentation for eg Random and can figure out the rest yourself.


    To generate a 6-digit number:

    Use Random and nextInt as follows:

    Random rnd = new Random();
    int n = 100000 + rnd.nextInt(900000);
    

    Note that n will never be 7 digits (1000000) since nextInt(900000) can at most return 899999 .

    So how do I randomize the last 5 chars that can be either AZ or 0-9?

    Here's a simple solution:

    // Generate random id, for example 283952-V8M32
    char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
    Random rnd = new Random();
    StringBuilder sb = new StringBuilder((100000 + rnd.nextInt(900000)) + "-");
    for (int i = 0; i < 5; i++)
        sb.append(chars[rnd.nextInt(chars.length)]);
    
    return sb.toString();
    

    If you need to specify the exact charactor length, we have to avoid values with 0 in-front.

    Final String representation must have that exact character length.

    String GenerateRandomNumber(int charLength) {
            return String.valueOf(charLength < 1 ? 0 : new Random()
                    .nextInt((9 * (int) Math.pow(10, charLength - 1)) - 1)
                    + (int) Math.pow(10, charLength - 1));
        }
    
    链接地址: http://www.djcxy.com/p/17658.html

    上一篇: 获取范围(x,y)中的随机整数?

    下一篇: 给定长度的Java随机数