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;

Recommended Answers

All 3 Replies

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, learning, and sharing knowledge.