aspose file tools*
The moose likes Beginning Java and the fly likes Array Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array Question" Watch "Array Question" New topic
Author

Array Question

MP Olsen
Greenhorn

Joined: Oct 21, 2004
Posts: 9


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

Joined: Dec 19, 2002
Posts: 229
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

Joined: May 25, 2001
Posts: 388
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

Joined: Aug 23, 2004
Posts: 69
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array Question