Random NumbersΒΆ
Games would be boring if the same thing happened each time you played the game. Games often use random numbers
to generate different possibilities. You need to know how to use the Math.random()
method to generate a random number. There are lots of mathematical methods
that you might want to use in your programs like Math.abs
(absolute value). These methods are in the Math
class and are static (class) methods so that you can call them by just using ClassName.methodName
.
Note
Class or static methods are in the object that defines the class (an object of a class named Class
) and can be accessed directly from the class. You do not need to create an object of the class to use them.
The Math.random()
method returns a number greater than or equal to 0.0, and less than 1.0. Try out the following code. Run it several times to see what it prints each time.
You can use Math.random
and a cast to integer to return a random number between some starting and ending value. The code below will return a random number from 0 to 9.
Note
Remember that a casting a double value to integer (int)
will throw away any values after the decimal point.
Run the code below several times to see how the value changes each time.
How could you change the code above to return a random number from 1 to 10? Modify the code above and see if your answer is correct.
Check your understanding

371: Which of the following is a correct test for a 40% possibility?
 (A) Math.random() < 0.4
 This is about 40% of the range from 0 to not quite 1 (which is what the Math.random method returns).
 (B) Math.random() > 0.4
 This will be about a 60% chance.
 (C) Math.random() == 0.4
 Do not use == with double values! Remember that Math.random can return any number between 0 and not quite 1 (about .99999999).