Generate random numbers in Java

Asked

Viewed 3,297 times

4

How to generate only numbers larger than 2?

How to generate only numbers larger than 2 and the generated numbers have to be multiples of 3(eg. 3, 6, 9)?

How to generate only numbers smaller than 10?

How to generate only numbers smaller than 10 and the generated numbers have to be multiples of 3(eg. 3, 6, 9)?

  • 1

    You can use the Random class?

  • can use the class Random: Random.nextInt(max - min + 1) + min where min would be 2, now the next situations I believe I should do checks on a recursive function to return only the desired results...

  • Yes. I can be with Random.

1 answer

7


Instantiating the class Random:

Random random = new Random();

How to generate only numbers larger than 2?

Between 2 and 1000, can replace the thousand or two for any value, for example:

numero = random.nextInt(1000) + 2;

How to generate only numbers larger than 2 and the generated numbers have to be multiples of 3 (e.g. 3, 6, 9)?

Between 3 and 3003 all multiples of 3.

numero = (random.nextInt(1000) + 1) * 3;

How to generate only numbers smaller than 10?

numero = random.nextInt(10); 

How to generate only numbers smaller than 10 and the generated numbers have to multiples of 3(eg. 3, 6, 9)?

numero = (random.nextInt(2)+1) * 3; 

Generate negative numbers, for example -5000 to 5000

numero = ((random.nextInt(2000)) * 5) - 5000;

Browser other questions tagged

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