you can use the Random class to generate random integers between 0 and N.
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class Example{
public static void main (String args[]) {
Example example= new Example();
//the following creates NON-RANDOM lists of integers, since
//Random objects are created in rapid succession with the same seed
//value taken from the system time.
for (int idx=0; idx<10; idx++) {
System.out.println("In range 0..9 (inclusive):" + example.pickNumber(10));
}
for (int idx=0; idx<10; idx++) {
System.out.println("In range 1..10(inclusive):" + example.pickNumberInRange(1,10));
}
//this list is indeed random
List numbers = example.pickNumbers(10, 5);
System.out.println("Random list built from ONE Random object:" + numbers);
}
/**
* Get a single random integer in the range 0 (inclusive) to N (exclusive).
*
* Important: if this method is called multiple times in rapid
* succession, it will return the SAME result.
*
* @param aUpperLimit must be greater than 0.
* @exception IllegalArgumentException if param does not comply.
*/
public int pickNumber( int aUpperLimit ){
if (aUpperLimit <=0) {
throw new IllegalArgumentException("UpperLimit must be positive: " + aUpperLimit);
}
//if the no-argument constructor is used, the seed is taken as
//the current time; thus, Random objects created in rapid succession
//in this way will have the same seed, and will generate the same sequence
//of random numbers.
Random generator = new Random();
return generator.nextInt(aUpperLimit);
}