Generate random number
Following java code will generate a random number between a given range. For instance if we want to generate a random number between 80, 100 we can use the following codes. In java to generate random number we have two options, using class Math or Random. We will see both examples
Using Class java.lang.Math
Math.random() generates a fraction(double) number between 0.0 and 1.0. We then add the lower bound to the product of (upperbound-lowerbound)*random_between0_1.
GenerateRandom1
private static int generateRandomInteger(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
double r = Math.random();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
Using Class java.util.Random
GenerateRandom2
private static int generateRandomIntegerII(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
Random random = new Random();
double r = random.nextDouble();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
Full Example
GenerateRandomNumber
import java.util.Random;
public class GenerateRandomNumber {
public static void main(String[] args) {
System.out.println(GenerateRandomNumber.generateRandomInteger(35, 40));
System.out.println(GenerateRandomNumber.generateRandomIntegerII(35, 40));
}
private static int generateRandomInteger(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
double r = Math.random();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
private static int generateRandomIntegerII(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
Random random = new Random();
double r = random.nextDouble();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
}
No comments :
Post a Comment
Please leave your message queries or suggetions.