How to generate a random number in Java between 1 and 10
There are many ways to generate a random number in Java.
- import java.util.Random;
- public class GenerateRandomNumbers {
- public static double getRandomDouble(int min, int max)
- {
- double x = Math.random();// generates number >=0 and <1
- return min + x*(max-min + 1);
- }
- public static double generateRandomDouble(int min, int max)
- {
- Random r = new Random();
- return min + r.nextDouble()*(max-min + 1);
- }
- //Only in Java 8
- public static int getRandomNumberInts(int min, int max){
- Random r = new Random();
- return r.ints(min,(max+1)).findFirst().getAsInt();
- //gets the first ints among a stream of random numbers within the specified range
- }
- //Only in Java 8
- public static double getRandomNumberDoubles(int min, int max){
- Random r = new Random();
- return r.doubles(min,(max+1)).findFirst().getAsDouble();
- //gets the first doubles among a stream of random numbers within the specified range
- }
- public static void main(String[] args) {
- int min = 1, max = 10;
- System.out.println("Random numbers");
- System.out.println("With math.random() : " + getRandomDouble(min, max));
- System.out.println("With Random class : " + generateRandomDouble(min, max));
- System.out.println("With Random ints() : " + getRandomNumberInts(min, max));
- System.out.println("With Random doubles() : " + getRandomNumberDoubles(min, max));
- }
- }
Output:
Random numbers
With math.random() : 5.488504869793829
With Random class : 5.057141318293521
With Random ints() : 9
With Random doubles() : 9.899763215404915
Source: Random Number Generation in Java - DZone Java
One interesting thing to note is that these only generate pseudo-random numbers. There has been attempts to generate truly random numbers.
This website generates random numbers based on atmospheric noise. True Random Number Service
Follow this question and related ones to know more
Can a computer generate a truly random number?