• 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

Array Question

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


The array is set up where I will get 20 random numbers between 1 and 60. How can I assure that I won't get the same number more than once.
[ December 01, 2004: Message edited by: MP Olsen ]
 
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You may want to test the value obtained from the method RandomNum() before inserting it into your array.

Consider using a data structure different from array (read: Vector/ArrayList) to make life simpler.

Regards,
Saket
 
Ranch Hand
Posts: 388
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi

use a java.util.Set implementation (e.g. HashSet) to "store" you numbers.
You can only add Objects to a Set so you need to create Integer (or Float, Double, Long,...) Objects from your random number.

Then you just keep adding numbers until the size of the Set has reached 20


You might want to get some information on the Object.hashCode() and Object.equals(Object obj) method to understand why equal Objects are only added once to the Set.

Hope that helps
Karl
 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey There!

Maybe this code can help you out a little, may not be the way you want to do it though. I am a beginner at java, but this is how I would do it.
Just make a Boolean Array the size of sixty and make it all false, once a number is generated it becomes true I put the little COLLISION OUTPUT so you can see that its working.



I think Java may set everything in the Boolean Array as false anyways.
Do not quote me on that though.

Hope This Helps

[ December 02, 2004: Message edited by: Sean Magee ]

[ December 02, 2004: Message edited by: Sean Magee ]

[ December 02, 2004: Message edited by: Sean Magee ]
[ December 02, 2004: Message edited by: Sean Magee ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic