This code example generates random numbers using the java.util.Random
class.
Here’s a step-by-step explanation of the code:
java.util.Random
class is imported so that it can be used in the code.main
method of the RandomNumbersExample
class is defined.rand
of the Random
class is created using the new
keyword.upperLimit
is declared and initialized with the value 10
. This variable will be used to specify the upper limit of the range of random numbers that will be generated.randomInteger
, randomFloat
, and randomDouble
are declared. The rand.nextInt(upperLimit)
method is called to generate a random integer, and the rand.nextFloat()
and rand.nextDouble()
methods are called to generate a random float and random double, respectively.System.out.println()
method.rand.nextInt(50)
method is called inside the loop to generate a random integer in the range 0 to 49. The generated random integer is then printed to the console.The output of the code will be 10 random numbers of different data types (integer, float, and double) and 10 random numbers in the range 0 to 49.
import java.util.Random;
public class RandomNumbersExample {
public static void main(String[] args) {
Random rand = new Random();
int upperLimit = 10;
int randomInteger = rand.nextInt(upperLimit);
float randomFloat = rand.nextFloat();
double randomDouble = rand.nextDouble();
System.out.println("random integer: " + randomInteger + "\nrandom float: " + randomFloat + "\nrandom double: "
+ randomDouble);
System.out.println("random numbers:");
for (int counter = 1; counter <= 10; counter++) {
System.out.print(rand.nextInt(50) + " ");
}
}
}
random integer: 3
random float: 0.2686128
random double: 0.20795575941751465
random numbers:
41 38 31 36 40 34 47 29 33 26
random integer: 6
random float: 0.71186566
random double: 0.8480369669637289
random numbers:
5 47 37 40 17 22 13 37 8 13