I am trying to generate random numbers in Java within a given range with the following code:
int randomNum = rand.nextInt((max - min) + 1) + min;
But this only generates numbers for me in the set of integers. How can I get numbers that are also decimals?
rand
should have a methodnextDouble
. This method accepts no arguments as it generates a number between 0.0 and 1.0. To adjust that number to your range you can use code similar to this:This is a very useful method, very important to use
nextDouble()
As an example:
Using the method described above, write 100 random numbers between the values 1.1 and 2.5:
see demo here!
could you use this
Which would create a random between 1 and 19 with decimals.
You can generate a random in which the minimum value is (
min + 100
) and then divide the number obtained by100.0
. In this way you would get a number with two decimal places:You can use this code , just be careful that this code will never give you the value of
max
:Use the class
Math
, though surely you could also use thenextDouble
class functionRandom
.