import java.util.Random; import java.lang.Math; // to get Math.abs(), used in Random2.nextInt /* Random2 * A class like Random, * but with a method int nextInt( int low, int high) */ class Random2 extends Random { // randBetween( low, high ) // return an int between low and high, inclusive. // public int nextInt( int low, int high ) { if (high < low) throw new RuntimeException( "Random2.nextInt: Need low <= high, but low,high=" + low + "," + high ); // nextInt() just returns an int between // Integer.MIN_VALUE and Integer.MAX_VALUE, inclusive. return ( Math.abs( nextInt() ) % (high - low + 1)) + low; } // Random2.main() // Test the Random2.nextInt( int, int ) routine. // static public void main( String[] args ) { int iterations = 10, upper = 3, lower = -2; Random2 r = new Random2(); System.out.println( "Here are " + iterations + " random ints between " + lower + " and " + upper + " inclusive." ); for ( int i = 0; i < iterations; i++ ) System.out.print( r.nextInt( lower, upper ) + ", " ); System.out.println(); System.out.print( "A random bit string: " ); for ( int i = 0; i < iterations; i++ ) System.out.print( r.nextInt( 0, 1 ) ); System.out.println(); System.out.println( "Here's 23: " + r.nextInt( 23, 23 ) ); System.out.println( "\nNow, time for an exception!" ); r.nextInt( 100, 99 ); } }