简体   繁体   English

从参数生成一定数量的随机数,然后将它们存储起来以便稍后在方法中调用

[英]Generate an amount of random numbers from a paramter then store them to call in a method later

I am trying to generate random numbers the amount determined by a paramter then store these numbers so i can assign them to a uniqe id field combined with a string code before eg user inputs code "HG-" and the number 4 the method will output HG-3981 or HG-8394 etc我正在尝试生成由参数确定的数量的随机数,然后存储这些数字,以便在例如用户输入代码“HG-”和数字 4 之前,我可以将它们分配给与字符串代码结合的 uniqe id 字段,该方法将输出 HG -3981 或 HG-8394 等

My attempt我的尝试

    {

        for (int i = 0; i == length; i++)
        {
            Random random = new Random();
            int rand = random.nextInt((9 - 1) + 1) + 1;

        }
        System.out.println(prefix + "-" + length);
    }

Instead of printing the length , shouldn't you be printing the rand variable?你不应该打印length ,而不是打印rand变量吗?

Example:例子:

System.out.println(prefix+"-"+rand);

Hope this helped!希望这有帮助!

This will generate 0 padded length digit integers:这将生成 0 个填充length数字整数:

    Random rand = new Random();
    int length = 6;

    DecimalFormat df = new DecimalFormat();
    df.setMaximumIntegerDigits(length);
    df.setMinimumIntegerDigits(length);
    df.setGroupingUsed(false);

    for (int i = 0; i < 50; i++) {
        System.out.println(df.format(rand.nextInt((int)Math.pow(10,length))));
    }

You will have to store these in order to ensure uniqueness.您必须存储这些以确保唯一性。

You can use any of Set<Integer> , int[10^length] , boolean[10^length] or BitSet(10^lenght) in order to record already generated numbers.您可以使用Set<Integer>int[10^length]boolean[10^length]BitSet(10^lenght)中的任何一个来记录已生成的数字。 Be mindful of process restarts etc.注意进程重启等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM