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

Показать описание
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
-Not very useful on its own, but the result it can be multiplied to give a "range" of number
-The upper bound is always excluded so you'd need to add 1 to get an inclusive range
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
-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"
-You can now use the formula like this:
(int)(generator .nextDouble()*range ) +min
-But you can also use get an integer in a specific range
-The formula can now be used like this
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
-Not very useful on its own, but the result it can be multiplied to give a "range" of number
-The upper bound is always excluded so you'd need to add 1 to get an inclusive range
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
-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"
-You can now use the formula like this:
(int)(generator .nextDouble()*range ) +min
-But you can also use get an integer in a specific range
-The formula can now be used like this
Комментарии