# Random int

• 02-07-2011, 06:19 PM
drucey
Random int
Hi guys, been looking online and can;t seem to find how to do what I want. I'm basically looking through methods but want to create a random number. I know how to limit its top end but not sure how to limit both:

For example a random number between 14-40.

Any help is appreciated!
• 02-07-2011, 06:39 PM
JosAH
Quote:

Originally Posted by drucey
Hi guys, been looking online and can;t seem to find how to do what I want. I'm basically looking through methods but want to create a random number. I know how to limit its top end but not sure how to limit both:

For example a random number between 14-40.

Any help is appreciated!

Think of it: you want a pseudo random number in the range 14-40; in your mind subtract 14 from both numbers: 0-26. If you can generate a pseudo random number in that range you can generate one in the original range: simply add 14 to it.

kind regards,

Jos
• 02-07-2011, 06:40 PM
sunde887
just add the lower end to the number. If you want to do 14-40, you do the random from 0 - 26, then add 14.
• 02-07-2011, 06:42 PM
drucey
Oh ok thanks. I did think of that just thought there may be a way to dictate the lower parameter!

Thanx Guys
• 02-07-2011, 06:48 PM
Fubarable
Quote:

Originally Posted by drucey
Oh ok thanks. I did think of that just thought there may be a way to dictate the lower parameter!

There is, and Jos and sunde887 show you how. ;)
• 02-07-2011, 08:09 PM
drucey
Thanks, got it.

One more quick thing - the random generator is throwing out random numbers. What if i didnt want it to pick the same number? I have created the array etc, and want an if statement to say if its equal to ANYTHING in the array?

Thanks guys
• 02-07-2011, 08:31 PM
JosAH
Quote:

Originally Posted by drucey
Thanks, got it.

One more quick thing - the random generator is throwing out random numbers. What if i didnt want it to pick the same number? I have created the array etc, and want an if statement to say if its equal to ANYTHING in the array?

There are two approaches to solve this little problem:

1) remember the numbers that were already genetated; if such a number is generated again, retry.

2) generate all possible numbers in some order and store them in a Collection (without repetition, the order doesn't mind) and call the Collections.shuffle( ... ) method.

kind regards,

Jos
• 02-07-2011, 09:52 PM