AP Computer Science Question #2 - Math.random()

<p>

</p>

<p>According to the answer key, the correct answer is B. However, I’m a little confused. I thought Math.random() would generate a number from 0 to 1, inclusive. This means that myList.size() becomes an obtainable value… which isn’t a valid index. Can someone tell me why my reasoning is wrong?</p>

<p>Math.random() generates a number from 0 to 1, inclusive on the left but exclusive on the right. In other words, it generates a nonnegative real number less than 1. So the answer is B.</p>

<p>So (int) doesn’t round the number up even if it’s, say, 7.99999? It basically just truncates the number?</p>

<p>(int) always truncates the number.</p>

<p>Everything but B will put you out of bounds.</p>