






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An in-depth exploration of java's random class, which generates pseudo-random numbers. It covers various methods like nextint(), nextdouble(), and their usage to generate random numbers within specific ranges. Examples and exercises are included to help students understand the concepts.
Typology: Study notes
1 / 10
This page cannot be seen from the preview
Don't miss anything!







Copyright 2008 by Pearson Education
Copyright 2008 by Pearson Education
The
Random
class
Class
Random
is found in the
java.util
package.
import java.util.*;
Example: Random rand = new Random();int randomNumber =
rand.nextInt(10)
;^
// 0-
Method name
Description
nextInt()
returns a random integer
nextInt(
max
)^
returns a random integer in the range [0,
max
)
in other words, 0 to
max
-1 inclusive
nextDouble()
returns a random real number in the range [0.0, 1.0)
Copyright 2008 by Pearson Education
Random
questions
Random rand = new Random();
A random number between 1 and 100 inclusive? int random1 = rand.nextInt(100) + 1;
A random number between 50 and 100 inclusive? int random2 = rand.nextInt(51) + 50;
A random number between 4 and 17 inclusive? int random3 = rand.nextInt(14) + 4;
Copyright 2008 by Pearson Education
Random
and other types
Example: Get a random GPA value between 1.5 and 4.0: double randomGpa =
rand.nextDouble()
code to randomly play Rock-Paper-Scissors:^ int r = rand.nextInt(3);if (r == 0) {
System.out.println("Rock"); } else if (r == 1) {
System.out.println("Paper"); } else {
System.out.println("Scissors"); }
Copyright 2008 by Pearson Education
Random
answer
Copyright 2008 by Pearson Education
Random
question
^
Write a multiplication tutor program.^
Ask user to solve problems with random numbersfrom 1-20. The program stops after an incorrect answer. 14 * 8 =
^112
Correct!5 * 12 =
^60
Correct!8 * 3 =
^24
Correct!5 * 5 =
^25
Correct!20 * 14 =
^280
Correct!19 * 14 =
^256
Incorrect; the answer was 266You solved 5 correctly
Copyright 2008 by Pearson Education
Random
answer 2
... // Asks the user one multiplication problem,// returning the answer if they get it right and 0 if not. public static int askQuestion(Scanner console, Random rand) {
// pick two random numbers between 1 and 20 inclusive int num1 = rand.nextInt(20) +
int num2 = rand.nextInt(20) +
System.out.print(num1 + " * "
int guess = console.nextInt();if (guess == num
System.out.println("Correct!");return num1 *
num2;
} else {
System.out.println("Incorrect; the correct answer
was " +
(num1 * num2));
return 0; } } }