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

TanUv90
TanUv90
66.4 هزار بار بازدید - 8 سال پیش - GitHub repo with examples
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/
8 سال پیش در تاریخ 1395/02/24 منتشر شده است.
66,448 بـار بازدید شده
... بیشتر