Questions on the multiple choice section may be phrased such that they ask you to generate numbers in a given range. See Random numbers on the AP CS A Exam for the technique to approach these.
Other questions start with an existing expression based on Math.random() and ask what range of values can be generated. To answer these questions:
Approach
-
Start with the range for an unmodified call to
Math.random(). This is adoublegreater than or equal to0.0and strictly less than1.0. -
Apply each operation from the expression to the range, one at a time, in the order they are applied in the expression.
Example 1
What range of values can the statement below assign to value?
int value = (int) (Math.random() * 15) + 3;
Step 1: Initial range
int value = Math.random();
// 0.0 <= value < 1.0
Note: The statement does not compile since Math.random() returns a double. That’s ok because this is an intermediate step.
Step 2: After multiplying
int value = Math.random() * 15;
// 0.0 <= value < 15.0
Multiplying 0.0 by 15 results in 0.0. Multiplying 1.0 by 15 results in 15.0.
Note: As in Step 1, this statement does not compile.
Step 3: After casting to an int
int value = (int) (Math.random() * 15);
// 0 <= value <= 14
Casting 0.0 to an int results in 0.
When a number strictly less than (not less than or equal to) 15.0 is cast to an int, the biggest number that can result is 14.
The range could be written as 0 <= value < 15, but it makes more sense to say <= 14 than < 15 for an int.
Note: This statement does compile, though it is not the final statement.
Step 4: After adding
int value = (int) (Math.random() * 15) + 3;
// 3 <= value <= 17
Adding 3 to 0 results in 3. Adding 3 to 14 results in 17.
This is the final range.
Note: This statement compiles and is the final statement.
Example 2
What values can the statement below assign to num?
int num = 4 + (int) (Math.random() * 3);
Step 1: Initial range
int num = Math.random();
// 0.0 <= num < 1.0
Step 2: After multiplying
int num = Math.random() * 3;
// 0.0 <= num < 3.0
Step 3: After casting
int num = (int) (Math.random() * 3);
// 0 <= num <= 2
Step 4: After adding
int num = 4 + (int) (Math.random() * 3);
// 4 <= num <= 6
The statement can assign the values 4, 5, or 6 to num.
Example 3
What range of values can the statement below assign to r?
int r = (int) (Math.random() * 10 + 6);
Step 1: Initial range
int r = Math.random();
// 0.0 <= r < 1.0
Step 2: After multiplying
int r = Math.random() * 10;
// 0.0 <= r < 10.0
Step 3: After adding
int r = Math.random() * 10 + 6;
// 6.0 <= r < 16.0
As discussed above, I don’t like structuring statements that use Math.random() this way. That doesn’t mean I can’t work with code that structures them this way.
Step 4: After casting
int r = (int) (Math.random() * 10 + 6);
// 6 <= r <= 15
This is the final range of values that the statement can assign to r.