Ask Question
30 August, 19:50

The code segment below is intended to randomly print one of the values 2, 4, 6, or 8 with equal probability.

int val = / * missing code * /;

val * = 2;

System. out. print (val);

Which of the following can be used to replace / * missing code * / so that the code segment works as intended?

a. Math. random () * 4 + 1

b. Math. random () * 8

c. (int) (Math. random () * 4)

d. (int) (Math. random () * 4 + 1)

e. (int) (Math. random () * 8 + 1)

+1
Answers (1)
  1. 30 August, 22:37
    0
    D. (int) (Math. random () * 4 + 1)

    Explanation:

    The first two options (A and B) will give a compiler error incompactible types since the Math. random () functions returns a double and val has been declared as an int. To overcome this, a type casting to integer is carried out. Option D (int) (Math. random () * 4 + 1) will return a value after been casted to an int of 1,2,3,4 which when this line val * = 2; is executed gives the expected output of 2,4,6 or 8.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “The code segment below is intended to randomly print one of the values 2, 4, 6, or 8 with equal probability. int val = / * missing code * ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers