Qu’est-ce que la méthode Math.random() en Java ?
0.0 ≤ random < 1.0
Veuillez noter que le nombre aléatoire est supérieur ou égal à 0,0 et inférieur à 1,0 .
Comment utiliser Math.random() en Java ?
Utiliser la méthode Math.random() est assez simple, même pour les débutants.Exemple 1
Regardons un exemple de base pour une compréhension claire.public class RandomTest {
public static void main(String[] args) {
double random1 = Math.random();
double random2 = Math.random();
System.out.println("First Random Number: " + random1);
System.out.println("Second Random Number: " + random2);
}
}
Sortir
Premier nombre aléatoire : 0,5486939400685561 Deuxième nombre aléatoire : 0,23550115674999972
Utilisation de la méthode random() dans une plage
L’appel de la méthode Math.random() semble assez explicite. Cependant, notre besoin de nombres aléatoires ne se situe pas toujours entre 0 et 1. Pour des problèmes réels, nous pouvons également opérer dans d’autres plages spécifiées. Regardons un exemple d'utilisation de la méthode Math.random() pour une plage donnée, disons 1 à 50.Exemple 2
public class RandomNumberInRange {
public static int getRandom(int min, int max) {
int range = (max - min) + 1;
int random = (int) ((range * Math.random()) + min);
return random;
}
public static void main(String[] args) {
// Let's play Ludo with 4 Players
int dieRoll = getRandom(1, 6);
System.out.println("Red's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Blue's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Green's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Yellow's Turn: " + dieRoll);
}
}
Sortir
Tour du Rouge : 3 Tour du Bleu : 2 Tour du Vert : 6 Tour du Jaune : 4
GO TO FULL VERSION