• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Random Numbers for Arrays??

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am having trouble getting the code below to do what i want. I need the code to randomly generate a number between 0 and 45, if the number is between 0 and 45 it will place it in the array. But how do I make it generate another number if the one before it is not between 0 and 45???
Cheers,Rik
int Game1 [] = new int [1000];
for(int counter = 0; counter < 1000 ; counter ++)
{
int num = (int)(Math.random()*100);
if((num > 0) && (num <= 45))
{
Game1[counter] = num;
}
}
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Hello, you have a couple of routes. One, just generate a random number in the range you need to begin with.

Remember, Math.random() generates a number in the this range: [0, 1). That's zero-inclusive to 1-exclusive. So, just multiply that generated number by whatever limit you want to specify a range of [0, someLimit) and then add one to your result to get the range of [1, someLimit] - that's 1-inclusive to someLimit-inclusive.
If you really wanted the method to pick random numbers from 0 to 99 and then only use a value when the number is between 1 and 45, you could define a method to generate a number. The method would use recursion to be certain the number is within the proper range. Something like:

Good Luck,
-Dirk Schreckmann
P.S. This initial response was generated in haste, don't take it as bug-proof yet. When I have time later I'll check it, or someone might correct any mistakes (if they exist) before then.
[ February 09, 2002: Message edited by: Dirk Schreckmann ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic