20.3k views
3 votes
Assume that rand is an object of the Random class.

Which of the following statements generates a random number in the [200..600] range?
(A) int number = rand.nextInt(200) + 600;
(B) int number = rand.nextInt(600) + 200;
(C) int number = rand.nextInt(400) + 200;
(D) int number = rand.nextInt(401) + 200;

1 Answer

6 votes

Final answer:

The correct statement to generate a random number in the range [200..600] is (D) int number = rand.nextInt(401) + 200; by first generating a number in [0..400] then adding 200.

Step-by-step explanation:

To generate a random number in the range [200..600], we need a solution that provides a lower limit of 200 and an upper limit of 600. Among the given options, the correct one is:

(C) int number = rand.nextInt(400) + 200;

The reasoning behind this is that rand.nextInt(400) generates a number in the range [0..399]. By adding 200 to this, we shift the range to [200..599]. Since we want to include 600, we actually need to increase the range by 1,

Thus the final answer is:

(D) int number = rand.nextInt(401) + 200;

This statement generates a random number in the range [0..400] (total 401 numbers), and then adds 200 to shift the range to [200..600], which includes the desired upper limit.

User Jleft
by
9.1k points