Introduction to Java using NetBeans Section 4 : Random Numbers |
Generating Random Numbers
A Dice ProgramCreate 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.
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
Generating Random Numbers in a RangeTo generate a random number in a range, the following formula is used: Math.floor(Math.random() *( highNum – lowNum + 1) + lowNum ExampleGenerate 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 |
Copy the Rubric to your Google Drive and add a link on your website