0

I'm trying to get a random number between the numbers 57 and 48, 90 and 65, and 122 and 97.

(int) (Math.random * (max-min) + 1);

This usually works, but when I use it to get the above numbers

(int) (Math.random() * (57-48) + 1);
(int) (Math.random() * (90-65) + 1);
(int) (Math.random() * (122-97) + 1);

I wind up with variables that are much to small. (examples: 5 , 14, 3, 15, and 8).

I don't understand why it isn't working with these specific numbers.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ethan Stedman
  • 11
  • 1
  • 6
  • 3
    Why not use `java.util.Random` instead? It's a lot more useful when you just want integers. – Kayaman Dec 12 '17 at 14:38
  • 2
    Your approach is fundamentally flawed. You need to add `min`, not 1... – Jon Skeet Dec 12 '17 at 14:39
  • So I need to do (57-48) + 48, instead of (57-48) + 1? – Ethan Stedman Dec 12 '17 at 14:40
  • Well that would give you a value in the range [48, 57), yes. Note that 57 will not be returned there - it's an exclusive upper bound. But rather than just take my word for it, you should think about *why* that's the case. Oh, and use `java.util.Random` or similar instead. – Jon Skeet Dec 12 '17 at 14:42
  • Check this out: https://stackoverflow.com/questions/7961788/math-random-explained – melanzane Dec 12 '17 at 14:55

1 Answers1

1
return Math.floor(Math.random() * (57 - 48 + 1)) + 48;
return Math.floor(Math.random() * (90 - 65 + 1)) + 65;
return Math.floor(Math.random() * (122 - 97 + 1)) + 97;

Does this do it for you?

Whit W
  • 74
  • 10
  • Good answers on Stack Overflow should include some explanation as to what the problem was and how your answer solves the problem. – Scott Marcus Jan 23 '18 at 19:17