In: Computer Science
(Using Random Class) The following UML Class Diagram describes the java Random class:
java.util.Random
+Random()
+Random(seed: long)
+nextInt(): int
+nextInt(n: int): int
+nextLong(): long
+nextDouble(): double
+nextFloat(): float
+nextBoolean(): boolean
Constructs a Random object with the current time as its
seed.
Constructs a Random object with a specified seed.
Returns a random int value.
Returns a random int value between 0 and n (exclusive).
Returns a random long value.
Returns a random double value between 0.0 and 1.0
(exclusive).
Returns a random float value between 0.0F and 1.0F
(exclusive).
Returns a random boolean value.
Using this class, do the following:
1. Generate and display 20 random numbers of type integer in the
range 0 to 50.
2. Generate and display 20 random numbers of type integer with seed
3 in the range 0 to 1000.
3. Generate and display 20 random numbers of type double in the
range 10 to 50.
Find the java code below.
import java.util.Random;
public class Main {
public static void main(String[] args) {
// 1. Generate and display 20 random numbers of type integer in the range 0 to 50.
// Random object without seed
Random r1 = new Random();
for(int i = 0; i < 20; i++) {
System.out.print(r1.nextInt(50) + " ");
}
System.out.println("\n");
// 2. Generate and display 20 random numbers of type integer with seed 3 in the range 0 to 1000.
// Random object with seed
Random r2 = new Random(3);
for(int i = 0; i < 20; i++) {
System.out.print(r2.nextInt(1000) + " ");
}
System.out.println("\n");
// 3. Generate and display 20 random numbers of type double in the range 10 to 50.
// Using random object r1 already created
for(int i = 0; i < 20; i++) {
System.out.print(10 + r1.nextDouble() * 40 + " ");
}
System.out.println("\n");
}
}
Find the sample output below.
28 2 43 28 24 4 5 13 19 44 42 24 33 20 1 46 24 26 24 35
734 660 210 581 128 202 549 564 459 961 585 882 277 614 981 806 576 137 886 99
37.95586903691559 11.056002651969926 12.90802376135236 39.329371016024865 11.79542394500035 16.000907178005185 40.46076168179505 15.754589814934462 41.05277774574501 23.961914717444607 28.139561994648687 21.057567619285212 24.18144968416432 18.976726663530293 47.97851622262206 33.648700512987816 42.02777490782347 30.605151003151544 38.97155624320471 47.33292110172936