Comment générer un entier aléatoire entre min et max en java?


Quelle méthode renvoie un int aléatoire entre un min et un max? Ou n'a pas une telle méthode existe pas?

Ce que je cherche est quelque chose comme ceci:

NAMEOFMETHOD (min, max) 

(où min et max sont ints)

Qui renvoie soemthing comme ceci:

8

(au hasard)

Si une telle méthode existe, pourriez-vous créer un lien vers la documentation pertinente avec votre réponse. grâce.

Mise à jour: atempting pour implémenter la solution complète dans la prochaine réponse, j'ai ceci:

class TestR
{
    public static void main (String[]arg) 
    {   
        Random random = new Random() ;
        int randomNumber = random.nextInt(5) + 2;
        System.out.println (randomNumber) ; 
    } 
} 

Je reçois toujours les mêmes erreurs du complier:

TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
        ^
TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
                            ^
TestR.java:6: operator + cannot be applied to Random.nextInt,int
        int randomNumber = random.nextInt(5) + 2;
                                         ^
TestR.java:6: incompatible types
found   : <nulltype>
required: int
        int randomNumber = random.nextInt(5) + 2;
                                             ^
4 errors

Qu'est-ce qui ne va pas ici?

Author: Santosh Kumar, 2010-03-15

7 answers

Construire un objet Aléatoire au démarrage de l'application:

Random random = new Random();

, Puis utilisez Aléatoire.nextInt(int):

int randomNumber = random.nextInt(max + 1 - min) + min;

Notez que les limites inférieure et supérieure sont inclusives.

 114
Author: Mark Byers, 2017-02-05 18:01:33

Vous pouvez utiliser Aléatoire.nextInt (n). Cela renvoie un int aléatoire dans [0, n). Il suffit d'utiliser max-min+1 à la place de n et d'ajouter min à la réponse donnera une valeur dans la plage souhaitée.

 16
Author: MAK, 2010-03-14 22:26:04
public static int random_int(int Min, int Max)
{
     return (int) (Math.random()*(Max-Min))+Min;
}

random_int(5, 9); // For example
 5
Author: Jupiter Kasparov, 2014-06-30 11:45:41

Comme les solutions ci-dessus ne prennent pas en compte le débordement possible de faire max-min lorsque min est négatif, voici une autre solution (similaire à celle de kerouac)

public static int getRandom(int min, int max) {

        if (min > max) {
            throw new IllegalArgumentException("Min " + min + " greater than max " + max);
        }

        return (int) ( (long) min + Math.random() * ((long)max - min + 1));
    }

Cela fonctionne même si vous l'appelez avec:

getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 
 4
Author: arcuri82, 2016-12-05 22:46:27

L'utilisation de la classe Aléatoire est la voie à suivre comme suggéré dans la réponse acceptée, mais voici une façon moins directe et correcte de le faire si vous ne vouliez pas créer un nouvel objet aléatoire :

min + (int) (Math.random() * (max - min + 1));
 0
Author: kerouac, 2016-09-13 18:26:19

Cela génère un entier aléatoire de taille psize

public static Integer getRandom(Integer pSize) {

    if(pSize<=0) {
        return null;
    }
    Double min_d = Math.pow(10, pSize.doubleValue()-1D);
    Double max_d = (Math.pow(10, (pSize).doubleValue()))-1D;
    int min = min_d.intValue();
    int max = max_d.intValue();
    return RAND.nextInt(max-min) + min;
}
 -2
Author: julius.kabugu, 2012-01-16 14:53:43

Importer java.util.Aléatoire;

 -5
Author: darlinton, 2010-03-14 23:34:22