programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# breaking down simple array random program

jon ninpoja
Ranch Hand
Posts: 291
3
hi guys,

did a silly little program to create 3 word lists then select a word from each to make a sentence
though its working and i got it right,a few lines are bothering me

heres my code:

int oneLength = wordListOne.length;  -- i know it works out how many words are in the list (is this a list or an array? i thought it looked like an array)
ok so the number of words in the list are going into variable oneLength,thats fine...

int rand1 = (int) (Math.random() * oneLength); -- integer variable rand1 = Math.random() but why * oneLength ...why is it multiplying? or is * used differently in this function?

String saidSentence = wordListOne[rand1] -- just takes the random word from the array and prints it out...i get this

Carey Brown
Saloon Keeper
Posts: 3323
46
From the API docs:
random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
So, if you multiply that by N you will get a value from 0.0 up to but less than N. Taking the integer truncation of that gives you an int from 0 up to and including N-1, which is the range of valid indices in an array of length N.

Using the new Random class is more succinct.

jon ninpoja
Ranch Hand
Posts: 291
3
thanks carey,

will keep that in mind

Campbell Ritchie
Marshal
Posts: 56546
172
There is more about the Random class and Math#random in this old thread.

 It is sorta covered in the JavaRanch Style Guide.