Java Random Tutorial (Math.random() vs Random Class nextInt() nextDouble() )

Veröffentlicht am: 13 Mai 2016
auf dem Kanal: TanUv90
66,886
596

GitHub repo with examples https://github.com/SleekPanther/java-...
Random numbers are a common part of many programs and games. (Yeah I know they're not truly "random" but pesudorandom numbers are the best computer can do)
There are 2 main ways: Using a static method of the built-in Math class, or creating a Random object & calling methods on that object

➣Math.random()
-The "Math" class is built-in (no need to import) so calling "Math.random()" gives you a double from 0 to 1
-Not very useful on its own, but the result it can be multiplied to give a "range" of number
-"Math.random()*10" gives a range of 10 so 0 through 9.99999
-The upper bound is always excluded so you'd need to add 1 to get an inclusive range
-"(int)(Math.random()*10)" casts the result to an integer
-or replace "(int)" with "Math.round()" or "Math.floor()"
-You can also change the lower bound by adding a number to the end: (int)(Math.random()*10)+10 yields numbers from 10 to 19 (20 is excluded)

int min = 5;
int max = 15;
int range = max - min +1;

-Range must be 1 greater than the range you want since the upper bound will always be excluded
(int)(Math.random()*range ) +min
-This will give you the desired result
-Negative values for min & max still work as long as you still add 1 to the range
-Getting decimals just involves removing the (int) casting
-You might want to round off the numbers to only display a few decimals


➣Random class
-Random generator = new Random();
-Creates a new Random object with reference variable "generator"
-don't forget to "import java.util.Random;"
-You can now use the formula like this:
(int)(generator .nextDouble()*range ) +min
-Unfortunately nextDouble() can't accept parameters so you basically just use it like Math.random()
-generator.nextInt() give you an integer in the range negative 2 billion to positive 2 billion
-But you can also use get an integer in a specific range
-generator.nextInt(5) yields numbers 0 to 4 (5 is excluded)
-The formula can now be used like this
-generator.nextInt(range) + min;


Details on Random https://docs.oracle.com/javase/7/docs...
Editor I used (Eclipse) https://eclipse.org/downloads/


Auf dieser Seite können Sie das Online-Video Java Random Tutorial (Math.random() vs Random Class nextInt() nextDouble() ) mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer TanUv90 13 Mai 2016 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 66,886 Mal angesehen und es wurde von 596 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!