80.4k views
3 votes
Which of the following statements will return a random odd number between 5 and 13 inclusive in Java?

A) int randomOdd = (int)(Math.random() * 10) + 5;
B) int randomOdd = (int)(Math.random() * 9) + 5;
C) int randomOdd = (int)(Math.random() * 9) + 4;
D) int randomOdd = (int)(Math.random() * 10) + 4

User Ben ODay
by
8.5k points

1 Answer

4 votes

Final answer:

While none of the provided options directly return a random odd number between 5 and 13 inclusive, we can use a modified version of option B to achieve this by generating a random index and selecting the corresponding odd number from an array containing the odd numbers within the given range.

Step-by-step explanation:

The question asks to identify which code snippet will return a random odd number between 5 and 13 inclusive in Java. Let's inspect each option and find the correct one:

  • A) This expression can return numbers between 5 and 14 inclusive, but not only odd ones.
  • B) int randomOdd = (int)(Math.random() * 9) + 5; This expression will generate numbers between 5 (inclusive) and 13 (exclusive), but we need to ensure that it only generates odd numbers.
  • C) This expression can return numbers between 4 and 12 inclusive, which is not entirely within the specified range.
  • D) This expression can generate numbers between 4 and 13 inclusive, but like option A, not only odd numbers.

None of the options directly provide a method to only produce odd numbers. However, we can modify option B to meet the requirement. Since we need an odd number, and the range of odd numbers between 5 and 13 inclusive is {5, 7, 9, 11, 13}, we can start by generating a random number that will represent the index in this set of odd numbers. Here is how we can do it:

int index = (int)(Math.random() * 5); // This will give us a number from 0 to 4.
int[] oddNumbers = {5, 7, 9, 11, 13};
int randomOdd = oddNumbers[index]; // This will select the odd number based on the random index.
User Rajnikant Kakadiya
by
8.0k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.