The Math Class: random() 🌶️🌶️
Math.random() returns a double value that is always greater than or equal to 0.0, and always strictly less than 1.0, written as [0.0, 1.0). That upper bound being EXCLUSIVE (never actually reaching 1.0) is the single most common source of off-by-one mistakes with this method, so pay close attention to it throughout this worksheet.
The standard pattern for generating a random int in an inclusive range, from min to max, is:(int)(Math.random() * (max - min + 1)) + min
Before building that expression yourself, the first two questions review two ideas it depends on.
1. What does (int)(7.9) evaluate to in Java?
2. Which of these best describes every possible value Math.random() can return?
3. Arrange these tokens to build a Java expression that generates a random int in the INCLUSIVE range from 0 to 7. (One token below is a distractor — a very common but incorrect version of this expression.)
Click a placed token to send it back. With drag-and-drop enabled, you can also drag tokens to reorder them.
4. Now arrange these tokens to build a Java expression that generates a random int in the INCLUSIVE range from 4 to 7 — the same range SIZE as the last question (4 possible values), just shifted up. (One token below is a distractor.)
Click a placed token to send it back. With drag-and-drop enabled, you can also drag tokens to reorder them.
5. Now arrange these tokens to build a Java expression that generates a random int in the INCLUSIVE range from 0 to max, where max is an int variable (already declared, holding some value you don't know in advance). (One token below is a distractor.)
Click a placed token to send it back. With drag-and-drop enabled, you can also drag tokens to reorder them.
6. Arrange these tokens to build a Java expression that generates a random int in the INCLUSIVE range from min to max. (One token below is a distractor, a very common but incorrect version of this expression.)
Click a placed token to send it back. With drag-and-drop enabled, you can also drag tokens to reorder them.
7. What is the range of possible int values (int)(Math.random() * 10) + 5 can produce?
8. A method generates a random int using (int)(Math.random() * (high - low + 1)) + low, where high and low are int parameters. If low = 20 and high = 29, what is the LARGEST possible value this expression can produce?
9. What does (int)Math.random() * 6 + 1 always evaluate to, no matter how many times you run it?
10. A method is meant to generate a random int representing a die roll — an inclusive range from 1 to 6 — using (int)(Math.random() * (max - min)) + min, called with max = 6 and min = 1. Every time this runs, it never actually produces a 6. Why not?
Your score for your class is recorded when you click Submit all — checking individual questions doesn't save it. You can submit again to improve your score; your best one counts.