2009-05-08 7 views

Répondre

3

Comme Marc dit, adaptez juste Random.nextInt(int), avec quelques contrôles de santé d'esprit:

public static int nextInt(Random rng, int lower, int upper) { 
    if (upper < lower) { 
     throw new IllegalArgumentException(); 
    } 
    if ((long) upper - lower > Integer.MAX_VALUE) { 
     throw new IllegalArgumentException(); 
    } 
    return rng.nextInt(upper-lower) + lower; 
} 
+0

pourquoi est-ce nécessaire? if ((long) supérieur - inférieur> Integer.MAX_VALUE) { throw nouveau IllegalArgumentException(); } – MahdeTo

+0

Merci Jon, Cela pourrait fonctionner pour moi. – Murali

+0

@MahdeTo: Envisager nextInt (rng, Integer.MIN_VALUE, Integer.MAX_VALUE) –

0

Eh bien, vous pouvez utiliser Random.nextInt(int) en spécifiant la plage, puis il suffit d'ajouter la valeur minimale? à savoir rand.nextInt (12) + 5

+0

rand.nextInt (max) + min est incorrect; cela renvoie des entiers supérieurs à max? – dfa

+0

C'est pourquoi j'ai utilisé le mot ** range **, pas max –

2

pas, mais vous pouvez l'avoir ainsi:

public static int randomInRange(int min, int max){ 
     return min+Random.next(max-min); 
} 
0

Appel à Random.Next(x, y) peut être traduit à quelque chose comme Random.nextInt(y - x) + x;

Questions connexes