Random Number Demonstration
By Nicholas Duchon
This little program demonstrates the range parameters in the
java.util.Random.nextInt (n) method.
// File:
RandomeDemoND.java
// Date: Jul 7, 2014
// Author: Nicholas
Duchon
// Purpose: demo
Random.nextInt behavior
import
java.util.Random;
import
java.util.Scanner;
import
java.util.Arrays;
public class
RandomDemoND {
static Random
rn = new Random (); // generally only this once
public static
void main (String args []) {
int num, max;
Scanner sc = new Scanner (System.in);
while (true) {
System.out.print ("\nnumber of numbers, max [0 to quit]: ");
num = sc.nextInt ();
if (num <= 0) break;
max = sc.nextInt ();
int [] arr = new int [num];
for (int i = 1; i <= num; i++) {
arr [i - 1] = rn.nextInt (max);
System.out.printf ("%5d", arr [i-1]);
if (i % 20 == 0) System.out.println ();
} // end for
Arrays.sort (arr);
System.out.println ("----- SORTED: ----------");
for (int i = 1; i <= num; i++) {
System.out.printf ("%5d", arr [i-1]);
if (i % 20 == 0) System.out.println ();
} // end for
}
// end loop
System.out.println ("bye.");
} // end main
} // end class
RandomDemoND
Here's a set of output:
number of
numbers, max [0 to quit]: 40 5
0 3 4
4 4 2
4 4 3
0 3 0
4 2 1
2 1 1
4 0
1 4 0
3 1 0
4 1 4
4 0 4
2 3 3
3 2 1
3 3
----- SORTED:
----------
0 0 0
0 0 0
0 1 1
1 1 1
1 1 2
2 2 2
2 3
3 3 3
3 3 3
3 3 4
4 4 4
4 4 4
4 4 4
4 4
number of numbers,
max [0 to quit]: 0
bye.
End - July 7, 2014