Java Math random ()

Die Java Math random () -Methode gibt einen Wert zurück, der größer oder gleich 0,0 und kleiner als 1,0 ist.

Die Syntax der random()Methode lautet:

 Math.random()

Hinweis : Die random()Methode ist eine statische Methode. Daher können wir die Methode direkt unter Verwendung des Klassennamens aufrufen Math.

zufällige () Parameter

Die Math.random()Methode akzeptiert keine Parameter.

random () Rückgabewerte

  • Gibt einen Pseudozufallswert zwischen 0,0 und 1,0 zurück

Hinweis : Die zurückgegebenen Werte sind nicht wirklich zufällig. Stattdessen werden Werte durch einen bestimmten Rechenprozess erzeugt, der eine Bedingung der Zufälligkeit erfüllt. Daher Pseudozufallswerte genannt.

Beispiel 1: Java Math.random ()

 class Main ( public static void main(String() args) ( // Math.random() // first random value System.out.println(Math.random()); // 0.45950063688194265 // second random value System.out.println(Math.random()); // 0.3388581014886102 // third random value System.out.println(Math.random()); // 0.8002849308960158 ) )

Im obigen Beispiel sehen wir, dass die random () -Methode drei verschiedene Werte zurückgibt.

Beispiel 2: Generieren Sie eine Zufallszahl zwischen 10 und 20

 class Main ( public static void main(String() args) ( int upperBound = 20; int lowerBound = 10; // upperBound 20 will also be included int range = (upperBound - lowerBound) + 1; System.out.println("Random Numbers between 10 and 20:"); for (int i = 0; i < 10; i ++) ( // generate random number // (int) convert double value to int // Math.round() generate value between 0.0 and 1.0 int random = (int)(Math.random() * range) + lowerBound; System.out.print(random + ", "); ) ) )

Ausgabe

 Zufallszahlen zwischen 10 und 20: 15, 13, 11, 17, 20, 11, 17, 20, 14, 14,

Beispiel 3: Zugriff auf zufällige Array-Elemente

 class Main ( public static void main(String() args) ( // create an array int() array = (34, 12, 44, 9, 67, 77, 98, 111); int lowerBound = 0; int upperBound = array.length; // array.length will excluded int range = upperBound - lowerBound; System.out.println("Random Array Elements:"); // access 5 random array elements for (int i = 0; i <= 5; i ++) ( // get random array index int random = (int)(Math.random() * range) + lowerBound; System.out.print(array(random) + ", "); ) ) )

Ausgabe

 Zufällige Array-Elemente: 67, 34, 77, 34, 12, 77,

Empfohlene Tutorials

  • Math.round ()
  • Math.pow ()
  • Math.sqrt ()

Interessante Beiträge...