This book is now obsolete Please use CSAwesome instead.

3.8. 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

You have attempted of activities on this page