Wednesday, April 9, 2008

Getting a random number from range


If you need to get a random number between X and Y, you should use some mathematical pattern using the Math Class and some calculus.

You can use this quick method to get the random number:

public int getRandomNumber(int min, int max) {
Random rnd;
rnd = new Random();
return min + Math.abs(rnd.nextInt()) % (max - min);
}


Another Method

Using the below code you can generate a 4 digit random integer.
int random4Digit = (int) (9 * Math.random())
+ (int) (9 * Math.random())
+ (int) (9 * Math.random())
+ (int) (9 * Math.random());

You can generate a 5 digit random int, by adding one more '(int) (9 * Math.random())'

No comments: