Consider the following code segment, which is intended to assign to num a random integer value between min and max, inclusive. Assume that min and max are integer variables and that the value of max is greater than the value of min. double rn = Math.random(); int num = /* missing code */; Which of the following could be used to replace /* missing code */ so that the code segment works as intended?

1 answer

To generate a random integer between min and max, inclusive, you can use the following formula:

int num = min + (int)(rn * (max - min + 1));

Here’s how it works:

  1. Math.random() generates a double between 0.0 (inclusive) and 1.0 (exclusive).
  2. Multiplying it by (max - min + 1) scales it to be in the range of 0 to (max - min + 1) (exclusive).
  3. When you cast this result to an integer, it effectively gives you a value in the range [0, max - min].
  4. Finally, adding min shifts this range up to [min, max].

So the complete line to replace the /* missing code */ would be:

int num = min + (int)(rn * (max - min + 1));

This ensures that num is uniformly distributed over the integers from min to max, including both endpoints.