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;
    }

Dani AI

Generated

: quick correction and a safer alternative.

The one-argument method is wrong: pass n to nextInt, not n-1. nextInt(bound) returns integers in [0, bound) and requires bound > 0. Using n-1 both drops the top value and makes a call to nextInt(0) when n == 1, which throws IllegalArgumentException. As suggested, check the API doc for nextInt to see the exact range and the precondition.

raised the inclusive/exclusive wording — important to be explicit. The two-argument approach is the common pattern: generate an offset of length end - start + 1 and add it to start so the result is inclusive of end. That is fine for most cases, but beware integer overflow when computing the length (for extreme values like start = Integer.MIN_VALUE and end = Integer.MAX_VALUE).

Safer implementations (avoid overflow and handle full int-span) — the first fixes the one-arg bug; the second uses long arithmetic and ThreadLocalRandom to avoid overflow:

public static int randomZeroToNminus1(int n) {
    if (n <= 0) throw new IllegalArgumentException("n must be > 0");
    return random.nextInt(n);
}
public static int randomInRangeInclusive(int start, int end) {
    if (start > end) throw new IllegalArgumentException("start <= end required");
    long range = (long) end - (long) start + 1L;
    long offset = java.util.concurrent.ThreadLocalRandom.current().nextLong(range);
    return (int) (start + offset);
}

Notes: ThreadLocalRandom is efficient and its nextLong(long bound) accepts large positive bounds (useful when the int-range might overflow). For cryptographic needs, use SecureRandom instead.

Recommended Answers

All 3 Replies

Be sure to clarify this. a <= N <= b or a < N < b?

Between or inclusive?

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.