Comment générer des entiers aléatoires dans une plage spécifique en Java

Mots clés : javarandomintegerjava-8java

meilleur 5 Réponses Comment générer des entiers aléatoires dans une plage spécifique en Java

vote vote

91

import java.util.concurrent.ThreadLocalRandom;  // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1); 
import java.util.Random;  /**  * Returns a pseudo-random number between min and max, inclusive.  * The difference between min and max can be at most  * <code>Integer.MAX_VALUE - 1</code>.  *  * @param min Minimum value  * @param max Maximum value.  Must be greater than min.  * @return Integer between min and max, inclusive.  * @see java.util.Random#nextInt(int)  */ public static int randInt(int min, int max) {      // NOTE: This will (intentionally) not run as written so that folks     // copy-pasting have to think about how to initialize their     // Random instance.  Initialization of the Random instance is outside     // the main scope of the question, but some decent options are to have     // a field that is initialized once and then re-used as needed or to     // use ThreadLocalRandom (if using at least Java 1.7).     //      // In particular, do NOT do 'Random rand = new Random()' here or you     // will get not very good / not very random results.     Random rand;      // nextInt is normally exclusive of the top value,     // so add 1 to make it inclusive     int randomNum = rand.nextInt((max - min) + 1) + min;      return randomNum; } 
vote vote

88

Min + (int)(Math.random() * ((Max - Min) + 1)) 
Math.random() * ( Max - Min ) 
Math.random() * 5 
Min + (Math.random() * (Max - Min)) 
5 + (Math.random() * (10 - 5)) 
Min + (int)(Math.random() * ((Max - Min) + 1)) 
5 + (int)(Math.random() * ((10 - 5) + 1)) 
vote vote

79

Random ran = new Random(); int x = ran.nextInt(6) + 5; 
vote vote

65

minimum + rn.nextInt(maxValue - minvalue + 1) 
vote vote

53

Random r = new Random(); int[] fiveRandomNumbers = r.ints(5, 0, 11).toArray(); int randomNumber = r.ints(1, 0, 11).findFirst().getAsInt(); 
public final class IntRandomNumberGenerator {      private PrimitiveIterator.OfInt randomIterator;      /**      * Initialize a new random number generator that generates      * random numbers in the range [min, max]      * @param min - the min value (inclusive)      * @param max - the max value (inclusive)      */     public IntRandomNumberGenerator(int min, int max) {         randomIterator = new Random().ints(min, max + 1).iterator();     }      /**      * Returns a random number in the range (min, max)      * @return a random number in the range (min, max)      */     public int nextInt() {         return randomIterator.nextInt();     } } 

Questions similaires