-3

for one of my assignments I am trying to generate a random number between 16-26 (both inclusive). I've read around and tried different methods but for some reason it goes over the specified range. This is what I have at the moment:

int dealerHand = 16 + (int) (Math.random() * ((26 - 16) + 16));

Any idea on why this isn't working? Thanks!

jaaytbe
  • 33
  • 6

2 Answers2

0

Try this:

Random r = new Random();
int dealerHand = 16 + r.nextInt(11);
user2023608
  • 470
  • 5
  • 18
0

((26 - 16) + 16) is the same as (26 + (-16 + 16) so 26 + 0, so now the problem should be more evident:

int dealerHand = 16 + (int) (Math.random() * 26);

which returns a number between 16 and 42.

What you need to do is closer to this:

int dealerHand = 16 + (int) (Math.random() * (26 - 16));

But watch out for the documentation of Math.random(): the returned number is >= 0.0 and < 1.0. Which means this code would generate numbers in the range [16;26) (that is, 26 is not included). As you want to include it this is the real formula:

int dealerHand = 16 + (int) (Math.random() * (26 - 16 + 1));
Daniel
  • 21,933
  • 14
  • 72
  • 101