+ 3
How can you get a random number between a given bound?
Imagine I want a number between 5 and 15. There are some methods, like java.util.Random nextInt () wich can give an upper bound, but I haven't found any method that let's you specify a lower bound.
6 Answers
+ 1
5 + (math.random()*10)
just specify the minimum before the range
if math.random give any number between 0 and 1
mult by 10 to enlarge the range to 0 till 10 and add 5 to make it 5 till 15
+ 1
I'm pretty sure Math.random () gives a number between 0 (inclusive) and 1 (not inclusive)? In that case would just multiplying by 11 fix it?
+ 1
if you multiply by 11 the range (after adding 5) will become from 5 (inclusive) till 16 (not inculsive)
if you want integers only you can mult by 11 and use the floor function or use (int) like Tdir wrote
if you want all of the numbers in the range (not just integers) including 15.... well tbh i'm not sure how to do it
+ 1
Thanks, integers are what I was looking for so it works for me
+ 1
(int) (Math.random() * 11) + 5)
This is if you only want the integers.
When you want al the numbers in the range you should not cast it to an integer and use it as a double or an other datatype.
+ 1
import java.util.Random // import Random class
Random rand = new Random(); // instantiate object
int randNum = rand.nextInt(4); // declare a variable randNum and initialize it to a random number between 0 and 3
I am told this is better than using math class, syntax is right I believe....still learning so did this from memory so just google Java random class if didn't work. đ