RandomInt.java


Below is the syntax highlighted version of RandomInt.java from §1.2 Built-in Types of Data.


/******************************************************************************
 *  Compilation:  javac RandomInt.java
 *  Execution:    java RandomInt N
 *
 *  Prints a pseudo-random integer between 0 and N-1.
 *  Illustrate an explicit type conversion (cast) from double to int.
 *
 *  % java RandomInt 6
 *  Your random integer is: 5
 *
 *  % java RandomInt 6
 *  Your random integer is: 0
 *
 *  % java RandomInt 1000
 *  Your random integer is: 129
 *
 *  % java RandomInt 1000
 *  Your random integer is: 333
 *
 ******************************************************************************/

public class RandomInt {
    public static void main(String[] args) {
        // a positive integer
        int n = Integer.parseInt(args[0]);

        // a pseudo-random real between 0.0 and 1.0
        double r = Math.random();

        // a pseudo-random integer between 0 and n-1
        int value = (int) (r * n);

        System.out.println(value);
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:12:06 EDT 2022.