• Post Reply Bookmark Topic Watch Topic
  • New Topic

breaking down simple array random program  RSS feed

 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks carey,


will keep that in mind
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is more about the Random class and Math#random in this old thread.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!