Generate random numbers in Java

4

How to generate only numbers greater than 2?

How to generate only numbers greater 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)?

    
asked by anonymous 28.10.2015 / 23:40

1 answer

7

Instantiating the class Random :

Random random = new Random();
  

How to generate only numbers greater than 2?

Between 2 and 1000, you can replace a thousand or two with any value, for example:

numero = random.nextInt(1000) + 2;
  

How to generate only numbers greater than 2 and the generated numbers must be   multiples of 3 (eg 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 must   be multiples of 3 (eg 3, 6, 9)?

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

Generate negative numbers, for example from -5000 to 5000

numero = ((random.nextInt(2000)) * 5) - 5000;
    
29.10.2015 / 02:23