Created: 2023-09-02 09:44
Status: #concept
Subject: Programming
Tags: Java Java Class java.util
java.util.Random
An instance of this class is used to generate a stream of pseudorandom numbers.
Get a Random Value with next___()
First, we have to instantiate a
new Random()
instance then use the instance.next___()
methods to get a random Java Data Type value.
nextBoolean()
nextDouble()
between0.0
and1.0
,[0.0, 1.0]
nextGaussian()
is similar, but the values are normally distributed.
nextFloat()
between0.0
and1.0
nextInt()
randomint
, unless we specifynextInt(bound)
so it returns a value between0
andbound - 1
, denoted as[0, bound)
.nextLong()
Getting Random Negative Numbers
We can use the nextInt
method to create diverse randomness. For example, we might need a program to give us a temperature between [-30,50]
. We can do this by first creating random a number between 0
and 80
and then subtracting 30
from it.
We shift the range by
MIN
to be within [0, MAX]
then subtract the resulting number with MIN
.
Random weatherMan = new Random();
int temperature = weatherMan.nextInt(81) - 30; // 81 because we want to include 80
System.out.println(temperature);