We would like to use Java Math class random()
to generate integers in range.
public class Main { public static void main(String[] args) { // your code here } }
public class Main { public static void main(String[] args) { System.out.println((int)(Math.random() * 10) ); System.out.println(50 + (int)(Math.random() * 50) ); } }
Math.random()
method generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random()
< 1.0).
We can use it to write a simple expression to generate random numbers in any range.
For example, returns a random integer between 0 and 9.
(int)(Math.random() * 10)
Returns a random integer between 50 and 99.
50 + (int)(Math.random() * 50)
In general, returns a random number between a and a + b, excluding a + b.
a + Math.random() * b