Generate random numbers in an Array from 10 to 50

Asked

Viewed 12,748 times

6

Since I can generate an array of random numbers with a limit, they should 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.

  • 1

    Substitute int i=0 for int i=10!

  • 1

    This is not possible because "i" controls the array position and not the numbers generated from Random.

  • 1

    True, I did. Take a look in that reply

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.
        }
  • 1

    Thank you, that’s just what I needed.

3

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

So if you come 0 adding 10 gets 10 (the minimum). and if you come 40 adding 10 gets 50 (the maximum).

1

The "formula" is

numRandomico = numMinimo + geraRandom(numMaximo-numMinimo)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.