简体   繁体   中英

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

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?

Example:

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

Hope this helped!

This will generate 0 padded length digit integers:

    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. Be mindful of process restarts etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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