how to generate a random long with 4 digits in java?

This question already has an answer here:

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

  • If you want to generate a number from range [0, 9999], you would use random.nextInt(10000) .

    Adding leading zeros is just formatting:

    String id = String.format("%04d", random.nextInt(10000));
    

    A Java int will never have leading 0 (s). You'll need a String for that. You could use String.format(String, Object...) or ( PrintStream.printf(String, Object...) ) like

    Random rand = new Random();
    System.out.printf("%04d%n", rand.nextInt(10000));
    

    The format String %04d is for 0 filled 4 digits. And Random.nextInt(int) will be [0,10000) or [0,9999].

    链接地址: http://www.djcxy.com/p/17670.html

    上一篇: 生成1到2之间的数字java Math.random()

    下一篇: 如何在java中生成一个4位数的随机长整型?