programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Tim Cooke
• Devaka Cooray
• Ron McLeod
• Jeanne Boyarsky
Sheriffs:
• Liutauras Vilda
• paul wheaton
• Junilu Lacar
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Piet Souris
• Carey Brown
• Tim Holloway
Bartenders:
• Martijn Verburg
• Frits Walraven
• Himai Minh

Generating random nos between a specific range

Ranch Hand
Posts: 230
• Number of slices to send:
Optional 'thank-you' note:
Hi is there a way by which i can generate a random no between a specific range.
I read that the class allows you to generate no between 0-n ie.(0-65) what if i want to generate random nos between 55-65 ??

Ranch Hand
Posts: 50
• 1
• Number of slices to send:
Optional 'thank-you' note:
First generate a random number and then map it to your range. If you want between 10 and 50
Random rand = new Random();
int min=10,max=50;
int num = rand.nextInt(max-min) + min;

Hope this helps!

Rajesh Khan
Ranch Hand
Posts: 230
• Number of slices to send:
Optional 'thank-you' note:
Thanks..

Marshal
Posts: 76872
366
• Number of slices to send:
Optional 'thank-you' note:
Nice touch, using max and min rather than number literals. You do realise that formula will never produce 50 as a result, only 49?

Ranch Hand
Posts: 50
• Number of slices to send:
Optional 'thank-you' note:

Campbell Ritchie wrote:Nice touch, using max and min rather than number literals. You do realise that formula will never produce 50 as a result, only 49?

Yes. And if you want to include 50 change the code to this..
int num = rand.nextInt(max-min+1) + min;

Campbell Ritchie
Marshal
Posts: 76872
366
• Number of slices to send:
Optional 'thank-you' note:
A lot of people don’t realise that. If you need 50, you have to include + 1.

 Don't get me started about those stupid light bulbs.