Using the Math Class

AP Computer Science A· difficulty 4/5

To get a random int in [a, b] (inclusive), use

  • A

    (int)(Math.random() * (b - a + 1)) + a

    check_circle
  • B

    (int)(Math.random() * (b - a)) + a

  • C

    (int) Math.random() * b + a

  • D

    (int)(Math.random() * b)

Explanation

Multiply by (b - a + 1) to include b; add a to shift range.

Want 10 more like this — adaptive to your weak spots?

Related questions