Generating Random Numbers
From Java Example Source Code
Contents |
[edit] Overview - Generating Random Numbers
This Java example program shows how to generate random numbers.
[edit] Java Source Code
- Package: sanchez.julio
- File: RandNum.java
package sanchez.julio; /* * Java Programming for Engineers Julio Sanchez Maria P. Canton * * * ISBN: 0849308100 Publisher: CRC Press */ // Java for Engineers // Filename: RandNum // Reference: Chapter 23 // Description: // Generating random numbers class RandNum { public static void main(String[] args) { int num; int[] dist = new int[10]; // Storage for distribution // Generate 10000 random numbers using Math.random() for (int x = 0; x < 10000; x++) { num = (int) (Math.floor(Math.random() * 10)); dist[num]++; } // Display distribution of random integers in the range // 0 to 9 System.out.println("Distribution using Math.random() "); for (int k = 0; k < 10; k++) System.out.print(k + "\t"); // Display results for (int y = 0; y < 10; y++) { System.out.print(dist[y] + "\t"); } System.out.println(); } }
[edit] What Result You Can Get
Run the program, you will get:
Distribution using Math.random() 0 1 2 3 4 5 6 7 8 9 1000 998 972 986 1044 959 960 1022 1043 1016
[edit] Required External Libraries and/or Files for this Java Example
Need nothing.
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
[edit] Question & Answer
Any question?
Click edit and post your question or answer here.
