Monday, January 9, 2017

Java How to generate random number in a range

In this post,  I will show you How to generate random in a range (integer range) via follwing ways.






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!


Share:

0 comments:

Post a Comment

Total Pageviews