Generate random numbers in an Array of 10 up to 50

6

How can I generate an array of random numbers with a limit, must be numbers from 10 to 50.

To generate random numbers from 0 to 50 I use:

            Random random = new Random();
            int array[] = new int[5]; // 5 números serão gerados.

            for (int i=0; i<array.length; i++) {
                 array[i] = random.nextInt(50); // Gera números aleatórios com limite 50.
                 System.out.println(array[i]); // Saída, são gerados 5 números.
            }

I would like to generate numbers from 10 up to a maximum of 50. instead of starting at 0.

    
asked by anonymous 25.08.2015 / 16:58

3 answers

9
 for (int i=0; i<array.length; i++) {
             array[i] = 10 + random.nextInt(40); // Gera números aleatórios com limite 50 e minimo 10.
             System.out.println(array[i]); // Saída, são gerados 5 números.
        }
    
25.08.2015 / 17:10
3

A very simple way is to make random.nextint(40) and always add 10 to the result.

So if it comes 0 adding 10 gets 10 (the minimum). and if it comes 40 adding 10 gets 50 (the maximum).

    
25.08.2015 / 17:06
1

The "formula" is

numRandomico = numMinimo + geraRandom(numMaximo-numMinimo)

    
25.08.2015 / 20:00