Casa > H > How To Generate A Random Number In Java Between 1 And 10

How to generate a random number in Java between 1 and 10

There are many ways to generate a random number in Java.

  1. import java.util.Random; 
  2.  
  3. public class GenerateRandomNumbers { 
  4.  
  5. public static double getRandomDouble(int min, int max) 
  6. double x = Math.random();// generates number >=0 and <1 
  7. return min + x*(max-min + 1); 
  8.  
  9.  
  10. public static double generateRandomDouble(int min, int max) 
  11. Random r = new Random(); 
  12. return min + r.nextDouble()*(max-min + 1); 
  13.  
  14. //Only in Java 8 
  15. public static int getRandomNumberInts(int min, int max){ 
  16. Random r = new Random(); 
  17. return r.ints(min,(max+1)).findFirst().getAsInt(); 
  18. //gets the first ints among a stream of random numbers within the specified range 
  19.  
  20. //Only in Java 8 
  21. public static double getRandomNumberDoubles(int min, int max){ 
  22. Random r = new Random(); 
  23. return r.doubles(min,(max+1)).findFirst().getAsDouble(); 
  24. //gets the first doubles among a stream of random numbers within the specified range 
  25.  
  26. public static void main(String[] args) { 
  27.  
  28. int min = 1, max = 10; 
  29. System.out.println("Random numbers"); 
  30. System.out.println("With math.random() : " + getRandomDouble(min, max)); 
  31. System.out.println("With Random class : " + generateRandomDouble(min, max)); 
  32. System.out.println("With Random ints() : " + getRandomNumberInts(min, max)); 
  33. System.out.println("With Random doubles() : " + getRandomNumberDoubles(min, max)); 
  34.  
  35.  

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?

De Anastas Tamashiro

Como são os capacetes SMK? :: O que é melhor, Huawei ou Samsung?