【问题标题】:how to generate a random long with 4 digits in java? [duplicate]java - 如何在java中生成4位数的随机长整数? [复制]
【发布时间】:2016-02-08 05:54:27
【问题描述】:

如何使用java中的随机类生成[0000,9999](含)范围内的long? long 必须是 4 位数字。

【问题讨论】:

    标签: java random


    【解决方案1】:

    Java int 永远不会有前导 0(s)。为此,您需要String。您可以使用 String.format(String, Object...) 或 (PrintStream.printf(String, Object...)) 之类的

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

    String%04d 的格式是 0 填充的 4 位数字。而Random.nextInt(int) 将是 [0,10000) [0,9999]。

    【讨论】:

      【解决方案2】:

      如果您想从 [0, 9999] 范围内生成一个数字,您可以使用random.nextInt(10000)

      添加前导零只是格式化:

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

      【讨论】:

      • 在上一个答案中,但不要忘记:Random random = new Random();
      猜你喜欢
      • 2016-03-11
      • 2011-03-19
      • 2012-09-21
      • 1970-01-01
      • 2012-12-02
      • 2011-12-10
      • 1970-01-01
      • 2011-04-12
      • 2015-01-28
      相关资源
      最近更新 更多