• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Question

 
MP Olsen
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • 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 ]
 
Saket Barve
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • 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
 
karl koch
Ranch Hand
Posts: 388
  • Mark post as helpful
  • send pies
  • 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
 
Sean Magee
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • 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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic