Introduction to Java using NetBeans

Section 4 : Random Numbers

 

Generating Random Numbers


Games, simulators, screen savers, and many other types of applications make use of random numbers.

Dice are a common element in many games. In this activity, you will use random numbers to create a program that simulates the roll of a pair of dice.

A Dice Program

Create the following form:

 

 

Investigating the random() Method

 

First import the Math function

import java.lang.Math;

The Roll Button



Run the program. Click on the Roll button a few times. Notice that output, (in the console window, not on the mainForm), is always a number between 0 and 1.

This shows random numbers between 0 and 1.

Test 2

Modify the previous statement to read the following.

Run the program again and click on the Roll button a few times. Notice that output is always a number between 0 and 6. We need to find a way to generate numbers from 1 to 6.

Test 3

Modify the previous statement to read the following.

Run the program again and click on the Roll button a few times. The Math.ceil() method returns the closest value that is greater than or equal to the number.

In the statement above, the Math.random() method is used first to generate a number between 0 and 1. Then we multiply that value by 6. The Math.ceil() method is then used to round UP the random number.  This guarantees that the resulting random number is in the range of 1 to 6. There is only one more problem; the value has a decimal and we want it to be an integer value.

Test 4

Modify the previous statement to read the following.

Run the program again and click on the Roll button a few times. Notice the addition of the (int) code before the Math.ceil method. This will take the result of the random calculation and turn it into an integer.

Completing the Program

 

This shows the finalized code for the random number generator.

Generating Random Numbers in a Range

To generate a random number in a range, the following formula is used:

Math.floor(Math.random() *( highNum – lowNum + 1) + lowNum

Example Icon Example

Generate random numbers from 5 to 20 inclusive.

System.out.println( Math.floor(Math.random() * 16 + 5) );

Assignment 4.1 Random Numbers

Create a form that prompts the user to enter the minimum and maximum values for their random numbers. The program should then calculate the random number and display it in the form.



For this assignment post the following:

1. Link to the Project Folder zipped
2. Link to the Jar File
3. The code for the JFrame Form
(Use http://www.planetb.ca/syntax-highlight-word to keep the code in the proper format)

Copy the Rubric to your Google Drive and add a link on your website