• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

selecting random elements from an array

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

I am sure this is really simple but I cannot work it out, although I have been searching the internet and books on Java

I have the following array and I want to be able to select a random element from it each time the method is called:



I just cannot think of a for loop to do this, so that it does not always pick the same position on the array.

Hope someone can help me with this

Thanks
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why would you need a for loop?

Add this line....



That should output a random value from the array each time.

Now you could do that or you could call this function that does the same thing.



[ August 03, 2005: Message edited by: Richard Anderson ]
[ August 03, 2005: Message edited by: Richard Anderson ]
 
son dunckley
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks very much for your response Richard - appreciate it

I don't know why I thought I needed a for loop either to print one line - having a funny moment(well several hours really!) :roll:
 
So you made a portal in time and started grabbing people. This tiny ad thinks that's rude:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic