How to Generate Random numbers in Java?
JDK provided a class Random to deal with Random numbers and you can use methods like nextInt(), nextDouble() etc to generate random numbers.
Here is a basic example.
public class RandomNumberJavaBasic {
public static void main(String[] args) {
System.out.println(Math.random());
}
}
How to Generate a Random number in a range?
The following class will generate random numbers within a specified range.
public class JavaRandomNumbersInARange {
public static void main(String[] args) {
System.out.println(randomInt(1,10));
}
public static int randomInt(int min, int max) {
Random randomNumGenerator = new Random();
int randomNum = randomNumGenerator.nextInt((max - min) + 1) + min;
return randomNum;
}
}
Random numbers has many uses in statistics, gaming , cryptography and gambling software.
No comments:
Post a Comment