How to generate random numbers in a range using Java
generate
random
number
java
Here is a simple method to generate a random number in a range using Java.
Code
package com.admfactory.basic;
import java.security.SecureRandom;
public class RandomNumberRangeGenerator {
private static SecureRandom random = new SecureRandom();
/**
* Return random number between min and max
*
* @param min
* the minimum value
* @param max
* the maximum value
* @return random number between min and max
*/
public static int random(int min, int max) {
return random.nextInt(max - min) + min;
}
public static void main(String[] args) {
System.out.println("Random numbers in range example");
System.out.println();
System.out.println("Random number between 10 and 20: " + random(10, 20));
System.out.println();
System.out.println("Random number between 100 and 200: " + random(100, 200));
}
}
Output
Random numbers in range example
Random number between 10 and 20: 14
Random number between 100 and 200: 156
Running the application multiple times you can see that the number will change.