So I am confused as to how to generate random integers between a range, in the first one it says to make the range from 0 to n-1 and the precondition is that n has to be greater than 0. For the second

  import java.util.Random ; 
 * This class represents a variety of methods that generate random integer values
 * @author 
 * @version 
public class RandomIntegers
  private static Random random = new Random();
  /** returns a random integer from 0 to n - 1
    * @param n the upper limit (exclusive)
    * Precondition: n > 0
    * @return a random integer from 0 to n - 1
    public static int randomInteger(int n)

            int rando = random.nextInt(n-1);

    return rando ;

  /** returns a random integer from start to end (inclusive)
    * @param start the lower limit of random numbers (inclusive)
    * @param end the upper limit of random numbers (inclusive)
    * Precondition: 0 <= start <= end
    * @return a random integer from start to end (inclusive)
    public static int randomInteger(int start, int end)
        return  random.nextInt((end - start) + 1) + start;

Edited by Reverend Jim: Moved to programming forum

7 Months
Discussion Span
Last Post by rproffitt

Between or inclusive?

The header docs seem clear on this.

Dietrich: You have code there, so what is your question exactly?

ps: HINT: You should check the API doc for Random's nextInt - specifically what range of values it returns.

Edited by JamesCherrill


Thanks JamesCherrill. My question is more to D since I've run into specs that call out "between 0 and 10" and the author really meant from 0 to 10. It's just one of those recurring spec vs. mindreading things you run into from time to time.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.