181k views
5 votes
Assume that rand is an object of the Random class.

Which of the following statements generates a random number in the [1..1000] range?
(A) int number = rand.nextInt(1000) + 1;
(B) int number = rand.nextInt(1000);
(C) int number = rand.nextInt(1001);
(D) int number = rand.nextInt(1) + 1000;

User Franca
by
7.8k points

1 Answer

3 votes

Final answer:

The correct statement to generate a random number in the range of [1..1000] is Option A: int number = rand.nextInt(1000) + 1; as it uses the nextInt method of the Random class which provides a number from 0 to 999, and with the addition of 1, it adjusts the range to 1 to 1000 inclusive.

Step-by-step explanation:

The student's question is regarding the generation of a random number in the given range of [1..1000] using an object of the Random class in Java. To generate a random number between 1 and 1000 inclusive using the Random class in Java, one would use the following code statement:

Option A: int number = rand.nextInt(1000) + 1;

This option correctly generates a random integer between 1 (inclusive) and 1001 (exclusive), which effectively corresponds to the range of [1..1000].

Step-by-step explanation:

  • The nextInt(int bound) method generates a random integer from 0 (inclusive) to the specified bound (exclusive).
  • nextInt(1000) generates a number between 0 and 999.
  • By adding 1 to the result, we adjust the range to 1 and 1000 inclusive.

Therefore, the correct answer is Option A.

User Sergionni
by
7.3k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.