These exercises are intended to follow Random numbers on the AP CS A Exam.
Exercise 1
a and b are of type double and
a >= 0.0 && b > a
Give code to declare double r and initialize it to a random value in the range
a <= r < b
Exercise 2
c and d are of type int and
c >= 0 && d > c
Give code to declare int r and initialize it to a random value in the range
c <= r <= d
Exercise 3
ArrayList<String> names = new ArrayList<String>();
names.add("Brandon");
names.add("Brenda");
/* code to add many more names to names */
Give code to remove and print a randomly selected name from names. Each name must be equally likely to be selected.
Exercise 4
The code below simulates rolling an 8 sided die.
int roll = (int) (Math.random() * 8) + 1;
The range of values generated is
1 <= roll <= 8
Which of the following correctly simulate(s) the result of rolling two 8 sided dice and adding the values together?
Case I: int sum = (int) (Math.random() * 8) + 1 + (int) (Math.random() * 8) + 1;
Case II: int sum = 2 + (int) (Math.random() * 8) + (int) (Math.random() * 8);
Case III: int sum = ((int) (Math.random() * 8) + 1) * 2;
(A) I only
(B) II only
(C) III only
(D) I and II only
(E) I, II, and III
Solution & comments
See the Random number exercise solutions or review them with AP CS Tutor Brandon Horn.