In programming, often we need to generate random numbers. All major languages provide functionality to generate pseudo-random numbers. In Java, this functionality is provided by java.util.Random. See example below:
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random rand = new Random();
rand.setSeed(12345);
System.out.println(rand.nextInt());
System.out.println(rand.nextDouble());
System.out.println(rand.nextInt(1111));
int x = rand.nextInt(501) + 500;
System.out.println(x);
}
}
output
1553932502
0.5132095356731635
241
555
First import java.util.Random. Instantiate an object of the class Random. Pseudo-random numbers are initialized with a numerical seed. setSeed() sets this seed. nextInt() return an integer. nextDouble returns a Double. nextInt(1111) will return a random number between 0 and 1110. If I want a random number between 500 and 1000 inclusive, I need to run nextInt(501) which will give me number 0 – 500 inclusive. Then simply add 500 to the generated number to get a random number between 500 and 1000 inclusive.