1. Java.util.Random
private static int getRandomNumberInRange(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
Example : getRandomNumberInRange(1,4) will generate 1,2,3,4.2. Math.Random
private static int getRandomNumberInRange(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
return (int)(Math.random() * ((max - min) + 1)) + min;
}
3. Random.ints (only Java8)private static int getRandomNumberInRange(int min, int max) {
Random r = new Random();
return r.ints(min, (max + 1)).findFirst().getAsInt();
}
Good luck!
0 comments:
Post a Comment