The Math Class
The
Math class holds methods for common calculations. A board game program needs several of them, for a die, two players on a track, and a square board.Using Math
Math sits in java.lang, and every program can use that package's classes by default. Every method in Math is a class method, so each call is written with the class name: Math.sqrt(64), and never sqrt(64) alone.Player A is on square 3 of the track and player B is on square 11.
int a = 3;
int b = 11;
int gap = Math.abs(a - b);
The difference
a - b is -8, and Math.abs returns its absolute value, 8. Since a - b is an int, the version of abs that takes an int runs and returns an int, so gap can be an int. With a double argument, Math.abs(-2.5) returns the double 2.5.pow and sqrt return doubles
The board has 64 squares in a square grid. Its side is
Math.sqrt(64), which is 8.0. A bonus doubles with each lap, and after 3 laps it's Math.pow(2, 3), which is 8.0.Both results are
double values, even with whole-number arguments, since that's the return type in each header. Printed, each one shows 8.0, and neither fits an int variable: int side = Math.sqrt(64); doesn't compile.Random integers
The game rolls a die with faces 1 through 6.
int roll = (int) (Math.random() * 6) + 1;
Take it one operation at a time.
Math.random() gives a value r with 0.0 <= r < 1.0. Multiplying by 6 stretches the range to 0.0 <= r * 6 < 6.0. The cast drops the fractional part, which leaves one of the six integers 0, 1, 2, 3, 4, or 5. Adding 1 gives 1 through 6, each as likely as the others. The top value is 6 and never 7, since the product is always less than 6.0.The multiplier is the number of values the range should have, and the number added is the smallest one. A spinner that lands on 10 through 15 has six values, so it's
(int) (Math.random() * 6) + 10.The parentheses around the product matter. Suppose the random value is 0.75. With the parentheses, the cast gets 0.75 times 6, which is 4.5, and keeps 4. Without them, the cast applies to 0.75 alone and gives 0, before the multiplication happens.
Random doubles
Without the cast, the result stays a
double. A timer limits each turn to a random time from 30.0 seconds up to, but not including, 45.0.double limit = Math.random() * 15 + 30;
Multiplying by 15 gives a value in
0.0 <= r * 15 < 15.0. Adding 30 shifts the range to 30.0 <= limit < 45.0. The lower end is included and the upper end isn't, exactly as with Math.random() itself.